C++ Classes and Objects

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++.

Classes in C++

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.

For example, let’s 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.

1. Data members are the data variables and member functions are the functions operating on these data variables.
2. Data members and member functions of a class are together called ‘class members’.

Creating Class in C++

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.

Syntax:
class ClassName {
Access specifier:                         //public, private or protected
    Data members;
    Member functions() {}
};

Example of a C++ class

class Student {
  public:
    int RollNo;
    string Name;
    int Age;
    void getDetails() {
      cout<< “Student Details\nRoll No.:” << RollNo << endl;
      cout<< “Name:” << Name << endl;
      cout<< “Age:” << Age << endl;
    }
};

Here, class Student contains data members RollNo, Name and Age, and member function getDetails()

In C++, we can define member functions in two ways:

1. Inside a class definition
2. Outside class definition

In the above example function getDetails() is defined inside class definition. Alternatively, we can define it outside class definition using scope resolution operator (‘::’) as follows:

Example of member function definition outside the class

class Student {
  public:
    int RollNo;
    string Name;
    int Age;
    void getDetails();
};
void Student::getDetails() {
  cout<< “Student Details\nRoll No.:” << RollNo << endl;
  cout<< “Name:” << Name << endl;
  cout<< “Age:” << Age << endl;
}

Objects in C++

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.

Taking the same example of a class of Mobiles as above, every Mobile in this case is an object of class Mobiles.

1. Data members and member functions of a class can be used and accessed by creating objects.

2. We can create multiple objects of a class.

Creating Objects in C++

Syntax:

ClassName ObjectName;

Let’s declare an object student1 of the class Student defined above.

Student student1;

The example given later in this article will help you in understanding how to create multiple objects of a class.

Accessing class members in C++

We can access data members and member functions using dot (‘.’) operator.

Syntax:

ObjectName.VariableName;		//Accessing data member
ObjectName.FunctionName();		//Accessing member function

For example, to access member function getDetails() of class Student defined above for object student1, we write

student1.getDetails();

Example to show how to create multiple objects of a class and how to access class members

#include <iostream>
using namespace std;
//Class
class Rectangle {
    public:                        		 //Access specifier
    double length, breadth;           //Data members
    double area() {                  	//Defining Member function
        return length*breadth;
    }
};
int main() {
    //Declaring an object
    Rectangle obj1;
    //Accessing data members by object 1
    obj1.length=12;
    obj1.breadth=8.5;

    //Declaring another object
    Rectangle obj2;
    //Accessing data members by object 2
    obj2.length=20;
    obj2.breadth=14;
    //Accessing member functions
    cout<<"Area of first rectangle = "<<obj1.area()<<endl;
    cout<<"Area of second rectangle = "<<obj2.area();
    return 0;
}

Output

Area of first rectangle = 102
Area of second rectangle = 280

Access Specifiers in C++

Access Specifiers in C++

Accessing a class member depends on its access control which is given using access specifiers. There are three types of access specifiers in C++:

a. Public: Data members and member functions declared as public are accessible from anywhere in the program.

b. Private: 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.

c. Protected: Protected class members are similar to private, except these can also be accessed by derived classes.

Example to illustrate the use of public and private in C++ class and how to initialize and display data through functions/methods

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

class Person {
    private:
    string name;
    int age;
    public:
    void insert(string n, int a) {     //function to initialize data
        name = n;
        age = a;
    }
    void display() {                       //function to display data
        cout<<"Name:"<<name<<endl;
        cout<<"Age:"<<age<<"yrs";
    }
};

int main() {
  Person p1;
  p1.insert("Vidvan", 10);
  p1.display();
  return 0;
}

Output

Name:Vidvan
Age:10yrs

Summary

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.

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.