C++ Classes and Objects C-PLUS-PLUS

C++ Classes and Objects  

C++ Classes and Objects

C++ Classes

A class in C++ is the building block, that leads to Object-Oriented programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A C++ class is like a blueprint for an object.

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.

For example, we Creating the MyClass using the keyword class as follows:

class MyClass{          // THE CLASS
   public:             // Access specifier
      int length;      // Attribute (int variable)
      double breadth;  // Attribute (double variable)
};

How to Create an C++ Object

In C++, an object is created from a class. We have already created the class named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name and to access the class attributes (length and breadth), use the dot syntax (.) on the object:

Example: Create an object called "myObj" and access the attributes:

#include <iostream>
#include <string>
using namespace std;

class MyClass {       // The class
  public:             // Access specifier
    int myNum;        // Attribute (int variable)
    string myString;  // Attribute (string variable)
};

int main() {
  MyClass myObj;  // Create an object of MyClass

  // Access attributes and set values
  myObj.length= 15;
  myObj.breadth= 20;

  // Printing the values
  cout << myObj.leangth<< "\n"; 
  cout << myObj.breadth; 
  return 0;
}
 

Output:

15

20

Note: You can use create multiple objects of the same class and can set different values to it's attributes.

Example:

MyClass myObj1;

MyClass myObj2;

myObj1.length= 15;

myObj2.length= 16;

 

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries