Articles

What is class and object in C++?

What is class and object in C++?


In this chapter of C++ interview questions, we will learn about:

  • what is class in c++?
  • what is object in c++?
  • syntax and example of class and object in c++

What is Class in C++?

Classes are expanding concepts of structure in C, they can contain data members also contain functions as members.

 

It is a new way of creating and implementing a user-defined data type.

 

Syntax for class:  

Class class-name {

  access_specifier1 member1;
  access_specifier2 member2;

};

access_specifier modify the acess rights for members.


What is object in c++?

A class provides the blueprints for objects, so basically an object is created from a class.

 

When a program is executed the objects interact by sending messages to one another.

 

Syntax for object: 

If a class name is Rectangle, then two objects of class Rectangle are:

  1. Rectangle R1;
  2. Rectangle R2;

Similarly we can create any number of objects as per our requirement.


Example of class and object in c++

In the below example of class and object in c++:

  • We have a class named 'Rectangle'
  • There are two objects created - R1 and R2
  • These objects will use the attributes defined in class like width and length according to their own requirements.
#include<iostream>
using namespace std;

class Rectangle //Class Declaration
{
public:
double width;
double length;
};

int main()
{
Rectangle R1;  //Object1
Rectangle R2;   //Object2
double area;

R1.width=5.0;
R1.length=7.0;
R2.width=10.0;
R2.length=12.0;

area=R1.width*R1.length;
cout<<"Area of Rectangle 1"<<" "<<area<<endl;

area=R2.width*R2.length;
cout<<"Area of Rectangle 2"<<" "<<area<<endl;

Output:

Area of Rectangle 1 35.0

Area of Rectangle 2 120.0

 

As shown above, we can create multiple other objects like R1 and R2 and define their own property i.e. width and length to use for specific purpose.


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Jan 16,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!