November 18, 2022

Class and Objects in C++

Posted on November 18, 2022  •  1 minutes  • 157 words

1. Class

  1. A class is a template(prototype) for the object.

  2. class is collection of data and its functions/methods

link

Syntax:

class ClassName
{
    // body of class

access_specifier:
    
    // data
    // methods / functions

};

Example:

class Rectangle
{
public:
    // data members
    double length;
    double width;

    // functions / methods
    double getArea()
    {
        return length * width;
    }
};

2. Objects

  1. Object is an instance of class.
  2. The allocation of memory only occurs when an object is created.

Syntax:

className objectName;

Example:

int main(){
    // create objects 
    Rectangle r1;
    Rectangle r2,r3;
}

Accessing Data Members and Functions through objects

We can access functions or data (public) by using . (dot) operator.

Syntax:

objectName.memberName;
objectName.functionName();

Example:

int main(){
    // create objects 
    Rectangle r1;
    
    // accessing the data members
    r1.length = 10;
    r1.width = 10;

    // accessing the member functions
    double area = r1.getArea();
    std::cout << "Area :" << area;

    return 0;
}
Follow me

I work on everything coding and share developer memes