Classes and Objects in C++

Classes and Objects in C++

Class in C++

A class is any functionality entity that defines its properties and functions. Class is a user-defined data type, which holds its own data member and member functions. Functions and variable declared inside the class declaration is said to be a member of the class

 C++ class is a blueprint for an object. Class id is defined as a group of similar objects.

 

 

Create a Class in C++

A class is declared using keyword class followed by the class name.

The body of the class is declared enclosed by pair of curly brackets and terminated by a semicolon at the end.

Syntax of Class in C++

class className {
   // some data
   // some functions
};

Example of Class in C++

class Student    
 {    
     public:  
     int id;  // data member     
     float salary; // data member  
     String name;// data member    
 }

Objects in C++

Objects are the fundamental blocks, it is associated with data and function which defines meaningful operators on the object.

The object is an instance of the class. When the program is executed the object interacts by sending messages to one another.

The object may represent a Person, Place, Bank account, etc. A class provides a blueprint for an object, so an object is created from a class. When we created a class there is no memory allocation, but when the object is created memory is allocated.

Syntax to Define Object in C++

className objectVariableName;

Example of Object in C++

void sampleFunction() {
    //  objects
    Room room1, room2;
}

int main(){
    //  objects 
    Room room3, room4;
}

Accessing data members and member functions

The accessing the data members and member functions of class using the dot(‘.’) operator with the object

Example of Accessing data members and member functions in C++

room2.calculateArea();

Program of Accessing data members and member functions

 
#include <bits/stdc++.h>
using namespace std;
class Study
{
    // Access specifier
    public:
 
    // Data Members
    string studyexperts;
 
    // Member Functions()
    void printname()
    {
       cout << "StudyExperts is: " << studyexperts;
    }
};
 
int main() {
 
    // Declare an object of class geeks
    Study obj1;
 
    // accessing data member
    obj1.studyexperts = "Kamya";
 
    // accessing member function
    obj1.printname();
    return 0;
}

Output

StudyExperts is: Kamya

 

Read more, Enumeration in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *