Oops Concept C++ Tahir Hanief Draboo - Tahir Draboo

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 66

TOPIC : OBJECT ORIENTED PROGREMMING CONCEPT

SUBMITTED TO : SUBMITTED BY :
AJAY SINGH NAME : TAHIR HANIEF
ASST. PROFESSOR MUR : 2304740
COURSE : B.TECH CSE
SECTION : B
Object Oriented Programming in C++

Object-oriented programming – As the name suggests uses objects


in programming. Object-oriented programming aims to implement
real-world entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOP is to bind together the data and
the functions that operate on them so that no other part of the code
can access this data except that function.
There are some basic concepts that act as the building blocks of
OOPs i.e.
 Class
 Object
 Encapsulation
 Abstraction
 Polymorphism
 Inheritance
 Dynamic Binding
 Message Passing
Characteristics of an Object-Oriented Programming Language
Class
The building block of C++ that leads to Object-Oriented programming
is a Class. It is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an
object. For Example: Consider the Class of Cars. There may be many
cars with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, etc. So here, the Car is the class, and wheels, speed
limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and
member functions.
 Data members are the data variables and member functions are
the functions used to manipulate these variables together
these data members and member functions define the
properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be
speed limit, mileage, etc and member functions can apply
brakes, increase speed, etc.
We can say that a Class in C++ is a blueprint representing a group of
objects which shares some common properties and behaviors.
Object
An Object is an identifiable entity with some characteristics and
behavior. An Object is an instance of a Class. When a class is defined,
no memory is allocated but when it is instantiated (i.e. an object is
created) memory is allocated.
C++
// C++ Program to show the syntax/working of Objects as a
// part of Object Oriented PProgramming
#include <iostream>
using namespace std;

class person {
char name[20];
int id;

public:
void getdetails() {}
};

int main()
{

person p1; // p1 is a object


return 0;
}
Objects take up space in memory and have an associated address like
a record in pascal or structure or union. When a program is executed
the objects interact by sending messages to one another. Each object
contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is
sufficient to know the type of message accepted and the type of
response returned by the objects.
To know more about C++ Objects and Classes, refer to this article
– C++ Classes and Objects
Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and
information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the
functions that manipulate them. Consider a real-life example of
encapsulation, in a company, there are different sections like the
accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all
the data related to finance. Similarly, the sales section handles all the
sales-related activities and keeps records of all the sales. Now there
may arise a situation when for some reason an official from the
finance section needs all the data about sales in a particular month.
In this case, he is not allowed to directly access the data of the sales
section. He will first have to contact some other officer in the sales
section and then request him to give the particular data. This is what
encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single
name “sales section”.

Encapsulation in C++
Encapsulation also leads to data abstraction or data hiding. Using
encapsulation also hides the data. In the above example, the data of
any of the sections like sales, finance, or accounts are hidden from
any other section.
To know more about encapsulation, refer to this article
– Encapsulation in C++
Abstraction
Data abstraction is one of the most essential and important features
of object-oriented programming in C++. Abstraction means displaying
only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only
knows that pressing the accelerator will increase the speed of the car
or applying brakes will stop the car but he does not know how on
pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation
of an accelerator, brakes, etc. in the car. This is what abstraction is.
 Abstraction using Classes: We can implement Abstraction in C+
+ using classes. The class helps us to group data members and
member functions using available access specifiers. A Class can
decide which data member will be visible to the outside world
and which is not.
 Abstraction in Header files: One more type of abstraction in C+
+ can be header files. For example, consider the pow() method
present in math.h header file. Whenever we need to calculate
the power of a number, we simply call the function pow()
present in the math.h header file and pass the numbers as
arguments without knowing the underlying algorithm according
to which the function is actually calculating the power of
numbers.
To know more about C++ abstraction, refer to this article
– Abstraction in C++
Polymorphism
The word polymorphism means having many forms. In simple words,
we can define polymorphism as the ability of a message to be
displayed in more than one form. A person at the same time can
have different characteristics. A man at the same time is a father, a
husband, and an employee. So the same person possesses different
behavior in different situations. This is called polymorphism. An
operation may exhibit different behaviors in different instances. The
behavior depends upon the types of data used in the operation. C++
supports operator overloading and function overloading.
 Operator Overloading: The process of making an operator
exhibit different behaviors in different instances is known as
operator overloading.
 Function Overloading: Function overloading is using a single
function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers,
sometimes there are 2 integers, and sometimes there are 3 integers.
We can write the Addition Method with the same name having
different parameters, the concerned method will be called according
to parameters.

Polymorphism in C++
To know more about polymorphism, refer to this article
– Polymorphism in C++
Inheritance
The capability of a class to derive properties and characteristics from
another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming.
 Sub Class: The class that inherits properties from another class
is called Sub class or Derived Class.
 Super Class: The class whose properties are inherited by a sub-
class is called Base Class or Superclass.
 Reusability: Inheritance supports the concept of “reusability”,
i.e. when we want to create a new class and there is already a
class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we
are reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Inheritance in C++
To know more about Inheritance, refer to this article – Inheritance in
C++
For a thorough grasp of OOP and how it’s applied in C++,
our Complete C++ Course offers detailed tutorials on mastering OOP
principles and implementing them in practical projects.
Dynamic Binding
In dynamic binding, the code to be executed in response to the
function call is decided at runtime. C++ has virtual functions to
support this. Because dynamic binding is flexible, it avoids the
drawbacks of static binding, which connected the function call and
definition at build time.
Example:
C++
// C++ Program to Demonstrate the Concept of Dynamic Binding
without virtual function
#include <iostream>
using namespace std;

class GFG {
public:
void call_Function() // function that calls print
{
print();
}
void print() // the display function
{
cout << "Printing the Base class Content" << endl;
}
};

class GFG2 : public GFG // GFG2 inherits publicly from GFG


{
public:
void print() // GFG2's display
{
cout << "Printing the Derived class Content" << endl;
}
};

int main()
{
GFG* geeksforgeeks = new GFG(); // Creating GFG's object using
pointer
geeksforgeeks->call_Function(); // Calling call_Function

GFG* geeksforgeeks2 = new GFG2(); // creating GFG2 object using


pointer
geeksforgeeks2->call_Function(); // calling call_Function for GFG2
object

delete geeksforgeeks;
delete geeksforgeeks2;

return 0;
}

Output
Printing the Base class Content
Printing the Base class Content
As we can see, the print() function of the parent class is called even
from the derived class object. To resolve this we use virtual functions.
Above Example with virtual Function:
C++
// C++ Program to Demonstrate the Concept of Dynamic binding
// with the help of virtual function

#include <iostream>
using namespace std;

class GFG
{
public:
// using "virtual" for the display function
virtual void print()
{
cout << "Printing the Base class Content" << endl;
}
// function that calls print
void call_Function()
{
print();
}
};
// GFG2 inherits publicly from GFG
class GFG2 : public GFG
{
public:
// GFG2's display
void print() override
{
cout << "Printing the Derived class Content" << endl;
}
};

int main()
{
// Creating GFG's object using pointer
GFG *geeksforgeeks = new GFG();
// Calling call_Function
geeksforgeeks->call_Function();

// creating GFG2 object using pointer


GFG *geeksforgeeks2 = new GFG2();
// calling call_Function for GFG2 object
geeksforgeeks2->call_Function();

delete geeksforgeeks;
delete geeksforgeeks2;

return 0;
}

Output
Printing the Base class Content
Printing the Derived class Content
Message Passing
Objects communicate with one another by sending and receiving
information. A message for an object is a request for the execution of
a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves
specifying the name of the object, the name of the function, and the
information to be sent.
Example:
C++
#include <iostream>
using namespace std;

// Define a Car class with a method to display its speed


class Car {
public:
void displaySpeed(int speed) {
cout << "The car is moving at " << speed << " km/h." << endl;
}
};

int main() {
// Create a Car object named myCar
Car myCar;

// Send a message to myCar to execute the displaySpeed method


int currentSpeed = 100;
myCar.displaySpeed(currentSpeed);

return 0;
}

//this code is contributed by Md Nizamuddin


Related Articles:
 Classes and Objects
 Inheritance
 Access Modifiers
 Abstraction
Advantage of OOPs over Procedure-oriented programming
language
Here are key advantages of Object-Oriented Programming (OOP) over
Procedure-Oriented Programming (POP):
1. Modularity and Reusability: OOP promotes modularity through
classes and objects, allowing for code reusability.
2. Data Encapsulation: OOP encapsulates data within objects,
enhancing data security and integrity.
3. Inheritance: OOP supports inheritance, reducing redundancy by
reusing existing code.
4. Polymorphism: OOP allows polymorphism, enabling flexible
and dynamic code through method overriding.
5. Abstraction: OOP enables abstraction, hiding complex details
and exposing only essential features

C++ Classes and Objects


Last Updated : 11 Oct, 2024


In C++, classes and objects are the basic building block that leads to
Object-Oriented programming in C++. In this article, we will learn
about C++ classes, objects, look at how they work and how to
implement them in our C++ program.
What is a Class in C++?
A class is a user-defined data type, which holds its own data
members and member functions, which can be accessed and used
by creating an instance of that class. A C++ class is like a blueprint for
an object.
For Example: Consider the Class of Cars. There may be many cars
with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed
Limit, Mileage range, etc. So here, the Car is the class, and wheels,
speed limits, and mileage are their properties.
 A Class is a user-defined data type that has data members and
member functions.
 Data members are the data variables and member functions are
the functions used to manipulate these variables together,
these data members and member functions define the
properties and behaviour of the objects in a Class.
 In the above example of class Car, the data member will
be speed limit, mileage, etc, and member functions can
be applying brakes, increasing speed, etc.
But we cannot use the class as it is. We first have to create an object
of the class to use its features. An Object is an instance of a Class.
Note: When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated.
To master classes and objects and their practical use, check out
our Complete C++ Course, where you’ll learn how to design and
implement object-oriented solutions.
Defining Class in C++
A class is defined in C++ using the keyword class followed by the
name of the class. The following is the syntax:
class ClassName {
access_specifier:
// Body of the class
};
Here, the access specifier defines the level of access to the class’s
data members.
Example
class ThisClass {
public:
int var; // data member
void print() { // member method
cout << "Hello";
}
};
If you want to dive deep into STL and understand its full potential,
our Complete C++ Course offers a complete guide to mastering
containers, iterators, and algorithms provided by STL.
What is an Object in C++?
When a class is defined, only the specification for the object is
defined; no memory or storage is allocated. To use the data and
access functions defined in the class, you need to create objects.
Syntax to Create an Object
We can create an object of the given class in the same way we
declare the variables of any other inbuilt data type.
ClassName ObjectName;
Example
MyClass obj;
In the above statement, the object of MyClass with name obj is
created.
Accessing Data Members and Member Functions
The data members and member functions of the class can be
accessed using the dot(‘.’) operator with the object. For example, if
the name of the object is obj and you want to access the member
function with the name printName() then you will have to write:
obj.printName()
Example of Class and Object in C++
The below program shows how to define a simple class and how to
create an object of it.
C++
// C++ program to illustrate how create a simple class and
// object
#include <iostream>
#include <string>

using namespace std;

// Define a class named 'Person'


class Person {
public:
// Data members
string name;
int age;

// Member function to introduce the person


void introduce()
{
cout << "Hi, my name is " << name << " and I am "
<< age << " years old." << endl;
}
};

int main()
{
// Create an object of the Person class
Person person1;
// accessing data members
person1.name = "Alice";
person1.age = 30;

// Call the introduce member method


person1.introduce();

return 0;
}

Output
Hi, my name is Alice and I am 30 years old.
Access Modifiers
In C++ classes, we can control the access to the members of the class
using Access Specifiers. Also known as access modifier, they are the
keywords that are specified in the class and all the members of the
class under that access specifier will have particular access level.
In C++, there are 3 access specifiers that are as follows:
1. Public: Members declared as public can be accessed from
outside the class.
2. Private: Members declared as private can only be accessed
within the class itself.
3. Protected: Members declared as protected can be accessed
within the class and by derived classes.
If we do not specify the access specifier, the private specifier is
applied to every member by default.
Example of Access Specifiers
C++
// C++ program to demonstrate accessing of data members
#include <bits/stdc++.h>
using namespace std;
class Geeks {
private:
string geekname;
// Access specifier
public:
// Member Functions()
void setName(string name) { geekname = name; }

void printname() { cout << "Geekname is:" << geekname; }


};
int main()
{
// Declare an object of class geeks
Geeks obj1;
// accessing data member
// cannot do it like: obj1.geekname = "Abhi";
obj1.setName("Abhi");
// accessing member function
obj1.printname();
return 0;
}

Output
Geekname is:Abhi
In the above example, we cannot access the data member geekname
outside the class. If we try to access it in the main function using dot
operator, obj1.geekname, then program will throw an error.
Member Function in C++ Classes
There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
Till now, we have defined the member function inside the class, but
we can also define the member function outside the class. To define
a member function outside the class definition,
 We have to first declare the function prototype in the class
definition.
 Then we have to use the scope resolution:: operator along with
the class name and function name.
Example
C++
// C++ program to demonstrate member function
// definition outside class
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
string geekname;
int id;

// printname is not defined inside class definition


void printname();

// printid is defined inside class definition


void printid() { cout << "Geek id is: " << id; }
};

// Definition of printname using scope resolution operator


// ::
void Geeks::printname()
{
cout << "Geekname is: " << geekname;
}
int main()
{

Geeks obj1;
obj1.geekname = "xyz";
obj1.id = 15;

// call printname()
obj1.printname();
cout << endl;

// call printid()
obj1.printid();
return 0;
}

Output
Geekname is: xyz
Geek id is: 15

Note that all the member functions defined inside the class definition
are by default inline, but you can also make any non-class function
inline by using the keyword inline with them. Inline functions are
actual functions, which are copied everywhere during compilation,
like pre-processor macro, so the overhead of function calls is
reduced.
Note: Declaring a friend function is a way to give private access to a
non-member function.
Constructors
Constructors are special class members which are called by the
compiler every time an object of that class is instantiated.
Constructors have the same name as the class and may be defined
inside or outside the class definition.
There are 4 types of constructors in C++ classes:
 Default Constructors: The constructor that takes no argument is
called default constructor.
 Parameterized Constructors: This type of constructor takes the
arguments to initialize the data members.
 Copy Constructors: Copy constructor creates the object from an
already existing object by copying it.
 Move Constructor: The move constructor also creates the
object from an already existing object but by moving it.
Example of Constructor
C++
// C++ program to demonstrate constructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;

//Default Constructor
Geeks()
{
cout << "Default Constructor called" << endl;
id=-1;
}

//Parameterized Constructor
Geeks(int x)
{
cout <<"Parameterized Constructor called "<< endl;
id=x;
}
};
int main() {

// obj1 will call Default Constructor


Geeks obj1;
cout <<"Geek id is: "<<obj1.id << endl;

// obj2 will call Parameterized Constructor


Geeks obj2(21);
cout <<"Geek id is: " <<obj2.id << endl;
return 0;
}

Output
Default Constructor called
Geek id is: -1
Parameterized Constructor called
Geek id is: 21
Note: If the programmer does not define the constructor, the
compiler automatically creates the default, copy and move
constructor.
Destructors
Destructor is another special member function that is called by the
compiler when the scope of the object ends. It deallocates all the
memory previously used by the object of the class so that there will
be no memory leaks. The destructor also have the same name as the
class but with tilde(~) as prefix.
Example of Destructor
C++
// C++ program to explain destructors
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
int id;

//Definition for Destructor


~Geeks()
{
cout << "Destructor called for id: " << id <<endl;
}
};

int main()
{
Geeks obj1;
obj1.id=7;
int i = 0;
while ( i < 5 )
{
Geeks obj2;
obj2.id=i;
i++;
} // Scope for obj2 ends here

return 0;
} // Scope for obj1 ends here

Output
Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7
Interesting Fact (Rare Known Concept)
Why do we give semicolons at the end of class?
Many people might say that it’s a basic syntax and we should give a
semicolon at the end of the class as its rule defines in cpp. But the
main reason why semi-colons are there at the end of the class is
compiler checks if the user is trying to create an instance of the class
at the end of it.
Yes just like structure and union, we can also create the instance of a
class at the end just before the semicolon. As a result, once execution
reaches at that line, it creates a class and allocates memory to your
instance.
C++
#include <iostream>
using namespace std;

class Demo{
int a, b;
public:
Demo() // default constructor
{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b) //parameterised constructor
{
cout << "parameterized constructor -values" << a << " "<< b <<
endl;
}

}instance;

int main() {

return 0;
}

Output
Default Constructor
We can see that we have created a class instance of Demo with the
name “instance”, as a result, the output we can see is Default
Constructor is called.
Similarly, we can also call the parameterized constructor just by
passing values here
C++
#include <iostream>
using namespace std;

class Demo{
public:
int a, b;
Demo()
{
cout << "Default Constructor" << endl;
}
Demo(int a, int b):a(a),b(b)
{
cout << "parameterized Constructor values-" << a << " "<< b <<
endl;
}

}instance(100,200);

int main() {

return 0;
}

Output
parameterized Constructor values-100 200
So by creating an instance just before the semicolon, we can create
the Instance of class.
C++ OOPs Concepts
The major purpose of C++ programming is to introduce the concept
of object orientation to the C programming language.
Object Oriented Programming is a paradigm that provides many
concepts such as inheritance, data binding, polymorphism etc.
The programming paradigm where everything is represented as an
object is known as truly object-oriented programming
language. Smalltalk is considered as the first truly object-oriented
programming language.

OOPs (Object Oriented Programming System)


Object means a real word entity such as pen, chair, table etc. Object-
Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For
example: chair, pen, table, keyboard, bike etc. It can be physical and
logical.
Class
Collection of objects is called class. It is a logical entity.
A Class in C++ is the foundational element that leads to Object-
Oriented programming. A class instance must be created in order to
access and use the user-defined data type's data members and
member functions. An object's class acts as its blueprint. Take the
class of cars as an example. Even if different names and brands may
be used for different cars, all of them will have some characteristics
in common, such as four wheels, a speed limit, a range of miles, etc.
In this case, the class of car is represented by the wheels, the speed
limitations, and the mileage.
Inheritance
When one object acquires all the properties and behaviours of
parent object i.e. known as inheritance. It provides code reusability.
It is used to achieve runtime polymorphism.
1. Sub class - Subclass or Derived Class refers to a class that
receives properties from another class.
2. Super class - The term "Base Class" or "Super Class" refers to
the class from which a subclass inherits its properties.
3. Reusability - As a result, when we wish to create a new class,
but an existing class already contains some of the code we
need, we can generate our new class from the old class thanks
to inheritance. This allows us to utilize the fields and methods
of the pre-existing class.
Polymorphism
When one task is performed by different ways i.e. known as
polymorphism. For example: to convince the customer differently, to
draw something e.g. shape or rectangle etc.
Different situations may cause an operation to behave differently.
The type of data utilized in the operation determines the behavior.
Advertisement
Abstraction
Hiding internal details and showing functionality is known as
abstraction. Data abstraction is the process of exposing to the
outside world only the information that is absolutely necessary while
concealing implementation or background information.For example:
phone call, we don't know the internal processing.
In C++, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is
known as encapsulation. For example: capsule, it is wrapped with
different medicines.
Encapsulation is typically understood as the grouping of related
pieces of information and data into a single entity. Encapsulation is
the process of tying together data and the functions that work with it
in object-oriented programming. Take a look at a practical illustration
of encapsulation: at a company, there are various divisions, including
the sales division, the finance division, and the accounts division. All
financial transactions are handled by the finance sector, which also
maintains records of all financial data. In a similar vein, the sales
section is in charge of all tasks relating to sales and maintains a
record of each sale. Now, a scenario could occur when, for some
reason, a financial official requires all the information on sales for a
specific month. Under the umbrella term "sales section," all of the
employees who can influence the sales section's data are grouped
together. Data abstraction or concealing is another side effect of
encapsulation. In the same way that encapsulation hides the data. In
the aforementioned example, any other area cannot access any of
the data from any of the sections, such as sales, finance, or accounts.
Dynamic Binding - In dynamic binding, a decision is made at runtime
regarding the code that will be run in response to a function call. For
this, C++ supports virtual functions.
Advantage of OOPs over Procedure-oriented programming language
1. OOPs makes development and maintenance easier where as in
Procedure-oriented programming language it is not easy to
manage if code grows as project size grows.
2. OOPs provide data hiding whereas in Procedure-oriented
programming language a global data can be accessed from
anywhere.
3. OOPs provide ability to simulate real-world event much more
effectively. We can provide the solution of real word problem if
we are using the Object-Oriented Programming language.
Why do we need oops in C++?
There were various drawbacks to the early methods of programming,
as well as poor performance. The approach couldn't effectively
address real-world issues since, similar to procedural-oriented
programming, you couldn't reuse the code within the program again,
there was a difficulty with global data access, and so on.
With the use of classes and objects, object-oriented programming
makes code maintenance simple. Because inheritance allows for
code reuse, the program is simpler because you don't have to write
the same code repeatedly. Data hiding is also provided by ideas like
encapsulation and abstraction.
Advertisement
Why is C++ a partial oop?
The object-oriented features of the C language were the primary
motivation behind the construction of the C++ language.
The C++ programming language is categorized as a partial object-
oriented programming language despite the fact that it supports OOP
concepts, including classes, objects, inheritance, encapsulation,
abstraction, and polymorphism.
1) The main function must always be outside the class in C++ and is
required. This means that we may do without classes and objects and
have a single main function in the application.
Advertisement
It is expressed as an object in this case, which is the first time Pure
OOP has been violated.
2) Global variables are a feature of the C++ programming language
that can be accessed by any other object within the program and are
defined outside of it. Encapsulation is broken here. Even though C++
encourages encapsulation for classes and objects, it ignores it for
global variables.
Overloading
Advertisement
Polymorphism also has a subset known as overloading. An existing
operator or function is said to be overloaded when it is forced to
operate on a new data type.
Conclusion
You will have gained an understanding of the need for object-
oriented programming, what C++ OOPs are, and the fundamentals of
OOPs, such as polymorphism, inheritance, encapsulation, etc., after
reading this course on OOPS Concepts in C++. Along with instances of
polymorphism and inheritance, you also learned about the benefits
of C++ OOPs.
C++ Object and Class
Since C++ is an object-oriented language, program is designed using
objects and classes in C++.

C++ Object
In C++, Object is a real world entity, for example, chair, car, pen,
mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here,
state means data and behavior means functionality.
Object is a runtime entity, it is created at runtime.
Advertisement
Object is an instance of a class. All the members of the class can be
accessed through object.
Let's see an example to create object of student class using s1 as the
reference variable.
1. Student s1; //creating an object of Student
Test it Now
In this example, Student is the type and s1 is the reference variable
that refers to the instance of Student class.

C++ Class
In C++, class is a group of similar objects. It is a template from which
objects are created. It can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
Test it Now

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It
creates instance of the class, initializes the object and prints the
object value.
Advertisement
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }
Test it Now
Output:
201
Sonoo Jaiswal

C++ Class Example: Initialize and Display data through method


Let's see another example of C++ class where we are initializing and
displaying object through method.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }
Test it Now
Output:
201 Sonoo
202 Nakul

C++ Class Example: Store and Display Employee Information


Let's see another example of C++ class where we are storing and
displaying employee information using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }
Test it Now
Output:
201 Sonoo 990000
202 Nakul 29000
C++ Constructor
In C++, constructor is a special method which is invoked
automatically at the time of object creation. It is used to initialize the
data members of new object generally. The constructor in C++ has
the same name as class or structure.
In brief, A particular procedure called a constructor is called
automatically when an object is created in C++. In general, it is
employed to create the data members of new things. In C++, the
class or structure name also serves as the constructor name. When
an object is completed, the constructor is called. Because it creates
the values or gives data for the thing, it is known as a constructor.
The Constructors prototype looks like this:
1. <class-name> (list-of-parameters);
Test it Now
The following syntax is used to define the class's constructor:
Advertisement
1. <class-name> (list-of-parameters) { // constructor definition }
Test it Now
The following syntax is used to define a constructor outside of a class:
1. <class-name>: :<class-name> (list-of-parameters){ // constructo
r definition}
Test it Now
Constructors lack a return type since they don't have a return value.
There can be two types of constructors in C++.
o Default constructor
o Parameterized constructor
C++ Default Constructor
A constructor which has no argument is known as default
constructor. It is invoked at the time of creating object.
Let's see the simple example of C++ default Constructor.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }
Test it Now
Output:
Advertisement
Default Constructor Invoked
Default Constructor Invoked
C++ Parameterized Constructor
A constructor which has parameters is called parameterized
constructor. It is used to provide different values to distinct objects.
Let's see the simple example of C++ Parameterized Constructor.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. Employee(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;
17. }
18. };
19. int main(void) {
20. Employee e1 =Employee(101, "Sonoo", 890000); //
creating an object of Employee
21. Employee e2=Employee(102, "Nakul", 59000);
22. e1.display();
23. e2.display();
24. return 0;
25. }
Test it Now
Output:
101 Sonoo 890000
102 Nakul 59000
What distinguishes constructors from a typical member function?
1. Constructor's name is the same as the class's
2. Default There isn't an input argument for constructors.
However, input arguments are available for copy and
parameterized constructors.
3. There is no return type for constructors.
4. An object's constructor is invoked automatically upon creation.
5. It must be shown in the classroom's open area.
6. The C++ compiler creates a default constructor for the object if
a constructor is not specified (expects any parameters and has
an empty body).
By using a practical example, let's learn about the various constructor
types in C++. Imagine you visited a store to purchase a marker. What
are your alternatives if you want to buy a marker? For the first one,
you ask a store to give you a marker, given that you didn't specify the
brand name or colour of the marker you wanted, simply asking for
one amount to a request. So, when we just said, "I just need a
marker," he would hand us whatever the most popular marker was in
the market or his store. The default constructor is exactly what it
sounds like! The second approach is to go into a store and specify
that you want a red marker of the XYZ brand. He will give you that
marker since you have brought up the subject. The parameters have
been set in this instance thus. And a parameterized constructor is
exactly what it sounds like! The third one requires you to visit a store
and declare that you want a marker that looks like this (a physical
marker on your hand). The shopkeeper will thus notice that marker.
He will provide you with a new marker when you say all right.
Therefore, make a copy of that marker. And that is what a copy
constructor does!
What are the characteristics of a constructor?
1. The constructor has the same name as the class it belongs to.
2. Although it is possible, constructors are typically declared in the
class's public section. However, this is not a must.
3. Because constructors don't return values, they lack a return
type.
4. When we create a class object, the constructor is immediately
invoked.
5. Overloaded constructors are possible.
6. Declaring a constructor virtual is not permitted.
7. One cannot inherit a constructor.
8. Constructor addresses cannot be referenced to.
9. When allocating memory, the constructor makes implicit calls
to the new and delete operators.
What is a copy constructor?
A member function known as a copy constructor initializes an item
using another object from the same class-an in-depth discussion on
Copy Constructors.
Every time we specify one or more non-default constructors (with
parameters) for a class, we also need to include a default constructor
(without parameters), as the compiler won't supply one in this
circumstance. The best practice is to always declare a default
constructor, even though it is not required.
A reference to an object belonging to the same class is required by
the copy constructor.
1. Sample(Sample &t)
2. {
3. id=t.id;
4. }
Test it Now
What is a destructor in C++?
An equivalent special member function to a constructor is a
destructor. The constructor creates class objects, which are
destroyed by the destructor. The word "destructor," followed by the
tilde () symbol, is the same as the class name. You can only define
one destructor at a time. One method of destroying an object made
by a constructor is to use a destructor. Destructors cannot be
overloaded as a result. Destructors don't take any arguments and
don't give anything back. As soon as the item leaves the scope, it is
immediately called. Destructors free up the memory used by the
objects the constructor generated. Destructor reverses the process of
creating things by destroying them.
The language used to define the class's destructor
1. ~ <class-name>()
2. {
3. }
Test it Now
The language used to define the class's destructor outside of it
C++ Object Oriented Programming
Being an object-oriented programming language, C++ uses objects to
model real-world problems
Unlike procedural programming, where functions are written to
perform operations on data, OOP involves creating objects that
contain both data and functions.
An object has two characteristics: attributes and behavior. For
example, a car can be an object. And, it has
 attributes - brand, model, size, mileage, etc.
 behavior - driving, acceleration, parking, etc.

C++ Class
A class is a blueprint for the object.
We can think of a class as the technical design (prototype) of a car. It
contains all the details about the brand, model, mileage, etc. We can
then build different cars based on these descriptions. Here, each
distinct car is an object.
An example for this can be:

A class named Car


class Car {
public:

// class data
string brand, model;
int mileage = 0;

// class function
void drive(int distance) {
mileage += distance;
}
};
In the above code, we have used the class keyword to create a class
named Car. Here,
 brand and model are class attributes used to store data
 drive() is a class function used to perform some operation
The public keyword represents an access modifier. To learn more,
visit C++ Access Modifiers.

C++ Objects
An object is an instance of a class.
For example, the Car class defines the model, brand, and mileage.
Now, based on the definition, we can create objects like
Car suv;
Car sedan;
Car van;
Here, suv, sedan, and van are objects of the Car class. Hence, the
basic syntax for creating objects is:
Class_Name object_name;

Example 1: Class and Objects in C++


#include <iostream>
using namespace std;

class Car {
public:
// class data
string brand, model;
int mileage = 0;

// class function to drive the car


void drive(int distance) {
mileage += distance;
}

// class function to print variables


void show_data() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Distance driven: " << mileage << " miles" << endl;
}
};

int main() {

// create an object of Car class


Car my_car;
// initialize variables of my_car
my_car.brand = "Honda";
my_car.model = "Accord";
my_car.drive(50);

// display object variables


my_car.show_data();

return 0;
}
Run Code
Output
Brand: Honda
Model: Accord
Distance driven: 50 miles
In this program, we have created a class Car with data members and
a member function. Also, we have created an object my_car of
the Car class.
Notice that we have used the dot operator . with the my_car object
in order to access the class members.
my_car.brand = "Honda";
my_car.model = "Accord";
my_car.drive(50);
my_car.show_data();
To learn more, visit our C++ Classes and Objects tutorial.

Basic Principles of C++ Object-Oriented Programming


The foundational principles of C++ OOP are:

Bundling of related data and functions together within a


Encapsulation
single entity.

Showing only the essential attributes of the class, while hid


Abstraction
the technical details from the user.

Using features from an existing class within a new class,


Inheritance
without modifying the existing class.

Ability of the same entity (function or operator) to behave


Polymorphism
differently in different scenarios.

Let's look at these principles in greater detail.

1. C++ Encapsulation
In C++, object-oriented programming allows us to bundle together
data members (such as variables, arrays, etc.) and its related
functions into a single entity. This programming feature is known as
encapsulation.
Encapsulation in C++
In Example 1, we bundled together the related
variables brand, model and mileage with the
function show_data() into a class named Car.
class Car {
public:

// class data
string brand;
string model;
int mileage = 0;

// class function
void show_data() {
// code
}
};
Encapsulation ensures that only member functions of a class can
access its data, which results in data hiding.
In C++, we hide data using the private and protected keywords. In
contrast, using the public keyword for certain class members makes
those members accessible to all other functions and classes.
To learn more, visit our C++ Encapsulation tutorial.

2. C++ Abstraction
In object-oriented programming, abstraction refers to the concept of
showing only the necessary information to the user i.e. hiding the
complex details of program implementation and execution.
For example, let us consider a slightly modified version of
the Car class:
class Car {
private:

// class data
int speed;

// class function
void show_car_status() {
// code
}
};
Suppose we want the show_car_status() function to show the status
of the car based on the value of the speed variable.
We can implement such conditional statements using
the if...else statement inside the show_car_status() function.
void show_car_status() {
if (speed != 0)
cout << "The car is being driven." << endl;
else
cout << "The car is stationary." << endl;
}
Here, we do not need to show the user all the codes we have written
to determine if the car is stationary or not; we just need to show
them whether the car is being driven or not depending on its speed.
In other words, we are only giving useful and relevant information to
the user, while hiding all the unnecessary details.
This is data abstraction in OOP.
To learn more about abstraction, visit our C++ Abstraction tutorial.
Note: Abstraction is not the same as data hiding. Abstraction is
showing only the relevant information, while data hiding is restricting
access to data members (variables, arrays, structures, etc.) so that
they cannot be accessed from outside the class.

3. C++ Inheritance
Inheritance in C++ allows us to create a new class (derived class) from
an existing class (base class).
The derived class inherits features from the base class and can have
additional features of its own.
To learn more, visit our C++ Inheritance tutorial.

Example 2: Use of Inheritance in C++


#include <iostream>
using namespace std;

// base class
class Vehicle {
public:

string brand;

void show_brand() {
cout << "Brand: " << brand << endl;
}
};

// derived class
class Car : public Vehicle {
public:

string model;

void show_model() {
cout << "Model: " << model << endl;
}
};

int main() {

// create an object of Car class


Car my_car;

// initialize variables of my_car


my_car.brand = "Honda";
my_car.model = "Accord";

// display variables of my_car


my_car.show_brand();
my_car.show_model();

return 0;
}
Run Code
Output
Brand: Honda
Model: Accord
Here,
 Vehicle is the base class.
 Car is the derived class.
The derived class inherits the features of the base class. We can see
this from the brand variable and the show_brand() function, since
the Car object my_car can access them.
In addition to the features of the base class, the derived class also
has features of its own. The unique features of the Car class are:
 model - a string variable
 show_model() - a function that prints the model variable.
We can also see that the Vehicle class has not been modified by its
derived class.
To learn more, visit our C++ Inheritance tutorial.

4. C++ Polymorphism
Polymorphism is the ability to use a common function (or operator)
in multiple ways.
In C++, polymorphism is implemented with the help of function
overloading, operator overloading, function overriding, and virtual
functions.
Let's look at function overriding as an example.
#include <iostream>
using namespace std;

// base class
class Shape {
public:

// function of base class


void shape_name() {
cout << "Shape" << endl;
}

};

// derived class
class Square : public Shape {
public:

// overriding function of derived class


void shape_name() {
cout << "Square" << endl;
}

};

int main() {

// create class objects


Shape shape;
Square square;

// call function from Shape class


shape.shape_name();

// call function from Square class


square.shape_name();

return 0;
}
Run Code
Output
Shape
Square
Here,
 Shape is the base class.
 Square is the derived class.
Both these classes have a function called shape_name(). But the
body of the shape_name() function are different in the two classes.
When the shape_name() function is called by the shape object, the
code inside the function of the Shape class is executed.
However, when shape_name() is called by the square object, the
code inside the body of Square class is executed.
Thus, we have used the same function shape_name() in two different
ways using C++ polymorphism.

You might also like