Oops Concept C++ Tahir Hanief Draboo - Tahir Draboo
Oops Concept C++ Tahir Hanief Draboo - Tahir Draboo
Oops Concept C++ Tahir Hanief Draboo - Tahir Draboo
SUBMITTED TO : SUBMITTED BY :
AJAY SINGH NAME : TAHIR HANIEF
ASST. PROFESSOR MUR : 2304740
COURSE : B.TECH CSE
SECTION : B
Object Oriented Programming in C++
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
{
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;
}
};
int main()
{
GFG* geeksforgeeks = new GFG(); // Creating GFG's object using
pointer
geeksforgeeks->call_Function(); // Calling call_Function
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();
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;
int main() {
// Create a Car object named myCar
Car myCar;
return 0;
}
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>
int main()
{
// Create an object of the Person class
Person person1;
// accessing data members
person1.name = "Alice";
person1.age = 30;
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; }
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;
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() {
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;
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.
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++ 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:
// 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;
class Car {
public:
// class data
string brand, model;
int mileage = 0;
int main() {
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.
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.
// 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() {
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:
};
// derived class
class Square : public Shape {
public:
};
int main() {
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.