{"id":81010,"date":"2021-06-14T09:00:02","date_gmt":"2021-06-14T03:30:02","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=81010"},"modified":"2021-06-14T09:00:02","modified_gmt":"2021-06-14T03:30:02","slug":"classes-and-objects-in-cpp","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/","title":{"rendered":"C++ Classes and Objects"},"content":{"rendered":"<p>We know that C++ is an object-oriented programming language i.e., in C++, we can wrap related data and functions together. Thus, classes and objects form the most important feature of C++. In this article, we will be discussing classes and objects in C++.<\/p>\n<h3>Classes in C++<\/h3>\n<p>The fundamental building block that leads to object-oriented programming in C++ is class. A class is a user-defined data type that contains its data members and member functions. A class is basically a blueprint of an object that declares and defines the characteristics and behavior of the object.<\/p>\n<p>For example, let\u2019s suppose a class of Mobiles, there are various types of mobiles but all have similar characteristics like memory, processor, camera, OS, etc. The class contains these characteristics as data members and behavior or related functions as member functions.<\/p>\n<p>1. Data members are the data variables and member functions are the functions operating on these data variables.<br \/>\n2. Data members and member functions of a class are together called \u2018class members\u2019.<\/p>\n<h4>Creating Class in C++<\/h4>\n<p>A class in C++ is defined using the keyword class followed by class name. The body of the class is defined inside curly braces and terminated using a semicolon.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">Syntax:\nclass ClassName {\nAccess specifier:                         \/\/public, private or protected\n    Data members;\n    Member functions() {}\n};\n<\/pre>\n<p><strong><span style=\"color: #000000\">Example of a C++ class<\/span><\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Student {\n  public:\n    int RollNo;\n    string Name;\n    int Age;\n    void getDetails() {\n      cout&lt;&lt; \u201cStudent Details\\nRoll No.:\u201d &lt;&lt; RollNo &lt;&lt; endl;\n      cout&lt;&lt; \u201cName:\u201d &lt;&lt; Name &lt;&lt; endl;\n      cout&lt;&lt; \u201cAge:\u201d &lt;&lt; Age &lt;&lt; endl;\n    }\n};\n<\/pre>\n<p>Here, class Student contains data members RollNo, Name and Age, and member function getDetails()<\/p>\n<p>In C++, we can define member functions in two ways:<\/p>\n<p>1. Inside a class definition<br \/>\n2. Outside class definition<\/p>\n<p>In the above example function getDetails() is defined inside class definition. Alternatively, we can define it outside class definition using scope resolution operator (\u2018::\u2019) as follows:<\/p>\n<p>Example of member function definition outside the class<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class Student {\n  public:\n    int RollNo;\n    string Name;\n    int Age;\n    void getDetails();\n};\nvoid Student::getDetails() {\n  cout&lt;&lt; \u201cStudent Details\\nRoll No.:\u201d &lt;&lt; RollNo &lt;&lt; endl;\n  cout&lt;&lt; \u201cName:\u201d &lt;&lt; Name &lt;&lt; endl;\n  cout&lt;&lt; \u201cAge:\u201d &lt;&lt; Age &lt;&lt; endl;\n}\n<\/pre>\n<h3>Objects in C++<\/h3>\n<p>An instance of a class is called an object. When a class is defined, no memory is allocated, we only define the specifications for its object. Memory is allocated when we create an object of a class.<\/p>\n<p>Taking the same example of a class of Mobiles as above, every Mobile in this case is an object of class Mobiles.<\/p>\n<p>1. Data members and member functions of a class can be used and accessed by creating objects.<\/p>\n<p>2. We can create multiple objects of a class.<\/p>\n<h4>Creating Objects in C++<\/h4>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">ClassName ObjectName;<\/pre>\n<p>Let\u2019s declare an object student1 of the class Student defined above.<\/p>\n<p>Student student1;<\/p>\n<p>The example given later in this article will help you in understanding how to create multiple objects of a class.<\/p>\n<h3>Accessing class members in C++<\/h3>\n<p>We can access data members and member functions using dot (\u2018.\u2019) operator.<\/p>\n<p><strong>Syntax:<\/strong><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">ObjectName.VariableName;\t\t\/\/Accessing data member\nObjectName.FunctionName();\t\t\/\/Accessing member function\n<\/pre>\n<p>For example, to access member function getDetails() of class Student defined above for object student1, we write<\/p>\n<p>student1.getDetails();<\/p>\n<p>Example to show how to create multiple objects of a class and how to access class members<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\nusing namespace std;\n\/\/Class\nclass Rectangle {\n    public:                        \t\t \/\/Access specifier\n    double length, breadth;           \/\/Data members\n    double area() {                  \t\/\/Defining Member function\n        return length*breadth;\n    }\n};\nint main() {\n    \/\/Declaring an object\n    Rectangle obj1;\n    \/\/Accessing data members by object 1\n    obj1.length=12;\n    obj1.breadth=8.5;\n\n    \/\/Declaring another object\n    Rectangle obj2;\n    \/\/Accessing data members by object 2\n    obj2.length=20;\n    obj2.breadth=14;\n    \/\/Accessing member functions\n    cout&lt;&lt;\"Area of first rectangle = \"&lt;&lt;obj1.area()&lt;&lt;endl;\n    cout&lt;&lt;\"Area of second rectangle = \"&lt;&lt;obj2.area();\n    return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Area of first rectangle = 102<br \/>\nArea of second rectangle = 280<\/div>\n<h3>Access Specifiers in C++<\/h3>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Access-Specifiers.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-81077\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/06\/Access-Specifiers.jpg\" alt=\"Access Specifiers in C++\" width=\"1050\" height=\"628\" \/><\/a><\/p>\n<p>Accessing a class member depends on its access control which is given using access specifiers. There are three types of access specifiers in C++:<\/p>\n<p>a. <strong>Public:<\/strong> Data members and member functions declared as public are accessible from anywhere in the program.<\/p>\n<p>b. <strong>Private<\/strong>: Private members of a class are accessible only by functions defined within the class. Any object or function outside the class cannot access private members. However, friend functions and friend classes can also access private members.<\/p>\n<p>c. <strong>Protected<\/strong>: Protected class members are similar to private, except these can also be accessed by derived classes.<\/p>\n<p>Example to illustrate the use of public and private in C++ class and how to initialize and display data through functions\/methods<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">#include &lt;iostream&gt;\n#include &lt;string&gt;\nusing namespace std;\n\nclass Person {\n    private:\n    string name;\n    int age;\n    public:\n    void insert(string n, int a) {     \/\/function to initialize data\n        name = n;\n        age = a;\n    }\n    void display() {                       \/\/function to display data\n        cout&lt;&lt;\"Name:\"&lt;&lt;name&lt;&lt;endl;\n        cout&lt;&lt;\"Age:\"&lt;&lt;age&lt;&lt;\"yrs\";\n    }\n};\n\nint main() {\n  Person p1;\n  p1.insert(\"Vidvan\", 10);\n  p1.display();\n  return 0;\n}\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<div class=\"code-output\">Name:Vidvan<br \/>\nAge:10yrs<\/div>\n<h3>Summary<\/h3>\n<p>From this article, we can understand that everything in C++ revolves around classes and objects. A class is the basis of object-oriented programming in C++ and objects are instances of a class.<\/p>\n<p>Here, we have covered syntax and examples for creating classes and objects in C++. We also discussed how to access data members and member functions of a class with sample codes to provide a better understanding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We know that C++ is an object-oriented programming language i.e., in C++, we can wrap related data and functions together. Thus, classes and objects form the most important feature of C++. In this article,&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":81076,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3405],"tags":[3503,3538,3539,3540],"class_list":["post-81010","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cpp","tag-access-specifiers-in-c","tag-c-classes","tag-c-objects","tag-objects-in-c"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>C++ Classes and Objects - TechVidvan<\/title>\n<meta name=\"description\" content=\"A class is a user-defined data type that contains its data members and member functions. Learn more about classes and objects in C++.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"C++ Classes and Objects - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"A class is a user-defined data type that contains its data members and member functions. Learn more about classes and objects in C++.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-14T03:30:02+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"C++ Classes and Objects - TechVidvan","description":"A class is a user-defined data type that contains its data members and member functions. Learn more about classes and objects in C++.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/","og_locale":"en_US","og_type":"article","og_title":"C++ Classes and Objects - TechVidvan","og_description":"A class is a user-defined data type that contains its data members and member functions. Learn more about classes and objects in C++.","og_url":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2021-06-14T03:30:02+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"C++ Classes and Objects","datePublished":"2021-06-14T03:30:02+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/"},"wordCount":657,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg","keywords":["Access Specifiers in C++","C++ Classes","C++ Objects","Objects in C++"],"articleSection":["C++ Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/","url":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/","name":"C++ Classes and Objects - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg","datePublished":"2021-06-14T03:30:02+00:00","description":"A class is a user-defined data type that contains its data members and member functions. Learn more about classes and objects in C++.","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2021\/06\/C-Classes-and-Objects.jpg","width":1200,"height":628,"caption":"C++ Classes and Objects"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/classes-and-objects-in-cpp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"C++ Classes and Objects"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81010","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=81010"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/81010\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/81076"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=81010"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=81010"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=81010"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}