Home C++ Object Oriented Programming in C++

Object Oriented Programming in C++

To deeply understand how real-world objects are related to programming, we must have an idea of object-oriented programming. So, what are objects? Objects are data items that comprise member functions and attributes.

Some important basic concepts of object oriented programming include:

  • Classes
  • Objects
  • Member Functions
  • Inline Functions
  • Constructors
  • Destructors

Classes

A class is a user-defined data type that defines how the object will be. Basically, a class is like a prototype for the object and consists of the attributes, i.e., variables and member functions of the class.

The basic syntax of a class is shown below:

class ClassName // Class declaration begins with
{ 
   private: // access specifier
   //some variables come here
   public: //access specifier
   //some member functions com here
};

We will understand the classes’ structure and development along with the tutorial, but let’s first discuss the access specifier.

Access Specifier

As we can see in the syntax, there are two keywords, private and public. These are the access specifiers because these keywords decide who can access the members of the class. The variables that come under the private specifier are accessed only inside the class, i.e., by the member functions of the class, and cannot be accessed in any other class or the main function. The variables or member functions that come under the public specifier are accessible outside the class and can be accessed in the main function and other classes.

If we omit the access specifier everything inside the class will come under the private specifier by default. Let’s continue with the construction of our class. In this tutorial, we will make a class called rectangle

#include <iostream>

using namespace std; 
// A class that defines the shape rectangle
class Rectangle
{
private:// access specifier will make both width and height as private variables
    // width and height declared i.e. they become attributes of the class
	int width;
	int height;

public:
// set_width function sets the value of width to the value entered by the user
int set_width(int w)//setter functions that start with the word set and sets the value
{
	width = w;
}
// set_height function sets the value of height
int set_height(int h)//setter functions that start with the word set and sets the value
{
	height = h;
}
// area is calculated
int get_area()
{
	return width * height;
}
// perimeter is calculated
int get_perimeter()
{
	return 2 * (width +  height);
}
}; // important to place semicolon at the end of a class

We have created a class called rectangle and have calculated the area and perimeter of it. An important thing to remember is that we cannot access width and height outside the class, so we cannot calculate the area or perimeter outside the class even if we want to. We can pass some values in the setter functions, give them some values, and call the main functions to calculate area.

The main program will work with the code shown above and displays the result of the above class.

int main()
{
	Rectangle r; // create an object r of the class Rectangle
  	//setting the value of width to 25 i.e. the variable width of the class now contains the value 25
	r.set_width(25); 
    //setting the value of width to 2
	r.set_height(2);
  	//calculating area and perimeter
	cout << "The area of rectangle is: " << r.get_area() << endl;
	cout << "The perimeter of rectangle is: " << r.get_perimeter() << endl;
}

Objects

An object is an instance of a class created with the definition statement after the class has been declared. A class is a blueprint of the object. The blueprint itself isn’t anything like the rectangle class alone, it is just a prototype of what the shape rectangle should have, but when we create the object r, we have created a rectangle.

Rectangle r; // this line creates an object of the class rectangle

A class can have multiple instances like r , r1 and so on. The member functions of the class can be accessed through a class object by using the dot operator. However, inside the class, the functions need not use the dot operator because the class variables are like normal variables for the member functions.

The class also uses getter and setter functions. The setter functions are shown in the code above. The getter functions are used to access the private variables of a class and returns the variable.

Inline Functions

Inline functions are functions that are defined within the scope of the class declaration. The functions in the above code are inline functions. However, a good approach would be that the prototype of the function should be declared inside the class, but the actual definition should be outside the class, as illustrated below:

// A Good Approach
// prototypes should be inside the class
int get_area();

//function definition outside the class
int Rectangle::get_area()
{
   return width * height;
}

The scope resolution operator (::) in the above example signifies that the function is a member function of the class.

Now a question arises that why should we use this method when we have inline functions?

The compiler treats inline functions differently and replaces every call to function with the function’s actual code. If we have called a certain function multiple times, the entire function body is inserted multiple times, thus increasing the program’s size.

Constructor

Constructor is a member function of the class that is called when the class object is created. If the programmer does not write the constructor, C++ creates an implicit constructor and is known as the default constructor. However, programmers tend to write their own constructor because it benefits from executing any code written in the constructor. C++ creates a default constructor; it is a good programming practice to make a default constructor. A class may have many parameterized constructors nut only one default constructor. Normally the default constructor has no parameters but can have parameters with default values such that no arguments need to be passed in the constructor.

A constructor is a function with the same name as the class and no return type. The program below illustrates an example of a default constructor. It is important to note that this class is an illegal declaration because it has 2 default constructors, which should not be the case.

 // This program below is an illegal declaration
 #include <iostream>
 using namespace std;

 class Shape
 {
 private:
 int length;
 public:
 Shape() // Default Constructor
 {
 cout << "Now the constructor is running.\n";
 }
 // Default constructor with arguments
 Shape(length = 5) {
 }
 };

 int main()
 {
 cout << "This is displayed before the object is created.\n";

 Shape sObj; // Define a Demo object
   
 cout << "This is displayed after the object is created.\n";
 return 0;
 }

Constructor Overloading

Overloading is when two functions of the same class have the same name but different parameters. Any functions in the class can be overloaded as well as constructors. A class can have multiple overloaded constructors. The example below highlights overloaded constructors.

// This program uses a constructor to initialize a member variable.
 #include <iostream>
 #include <cmath>
 using namespace std;

 // Circle class declaration
 class Circle { 
 private:
   double radius;

 public: // Member function prototypes
   //Overloaded constructors
   //default constructor
   Circle() { 
   }
   //parametrized constructor
   Circle(int r) {
     radius = r;
   }
   
   double getArea() {
     return 3.14 * pow(radius, 2);
   }
 };
int main()
 {
   // parametrized constructor called and sets the value of radius to 5
   Circle circle1(5);
   // Get and display each circle's area
   cout << "The area of circle1 is " << circle1.getArea() << endl;

   return 0;
 }

Destructor

A destructor is a function that is automatically called when the object is destroyed. Like constructors, the destructors also have the same name as the class. So how can we differentiate between a constructor and a destructor? Well, a destructor has a tilde(~) character before the function.

A destructor of class shape is shown below:

~Shape() {

}

Unlike constructors, no arguments can be passed inside a destructor; therefore, a program can have only one destructor. Destructors come in handy when we use dynamically allocated objects.

Conclusion

I hope you enjoyed this tutorial giving you insight into the basic concepts of object-oriented programming. Stay tuned to Code Underscored to learn mode on C++ programming. If you enjoyed this tutorial, please share it with your friends and spread the word. It means a lot to us.

You may also like

1 comment

Kevin Harper January 28, 2021 - 6:54 am

Thank you!! ❤️ Great article love your work

Reply

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More