0% found this document useful (0 votes)
7 views

Object Oriented Progra

C++ is a cross-platform, high-performance programming language developed as an extension of C, emphasizing object-oriented programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It is widely used in various applications, including operating systems and embedded systems, and supports features like namespaces and data abstraction. Key concepts include classes, objects, access specifiers, and constructors, which help manage data and functionality effectively.

Uploaded by

xfmgfrhtxt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Object Oriented Progra

C++ is a cross-platform, high-performance programming language developed as an extension of C, emphasizing object-oriented programming (OOP) principles such as encapsulation, inheritance, and polymorphism. It is widely used in various applications, including operating systems and embedded systems, and supports features like namespaces and data abstraction. Key concepts include classes, objects, access specifiers, and constructors, which help manage data and functionality effectively.

Uploaded by

xfmgfrhtxt
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Object Oriented Programming

What is C++?

C++ is a cross-platform language that can be used to create high-performance applications.

C++ was developed by Bjarne Stroustrup, as an extension to the C language.

C++ gives programmers a high level of control over system resources and memory.

Why Use C++?

C++ is one of the world's most popular programming languages.

C++ can be found in today's operating systems, Graphical User Interfaces, and embedded systems.

C++ is an object-oriented programming language which gives a clear structure to programs and allows
code to be reused, lowering development costs.

C++ is portable and can be used to develop applications that can be adapted to multiple platforms.

Difference between OOP and POP:

OOP POP

Object oriented. Structure oriented.

Program is divided into objects. Program is divided into functions.

Bottom-up approach. Top-down approach.

Inheritance property is used. Inheritance is not allowed.

It uses access specifier. It doesn‟t use access specifier.

Encapsulation is used to hide the data. No data hiding.

Concept of virtual function. No virtual function.

Object functions are linked through message Parts of program are linked through parameter
passing. passing.
OOP POP

Adding new data and functions is easy Expanding new data and functions is not easy.

The existing code can be reused. No code reusability.

Use for solving big problems. Not suitable for solving big problems.

C++, Java. C, Pascal.

Basic Data Types:

Data Size Description


Type

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

int 2 or 4 Stores whole numbers, without decimals


bytes

float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15
decimal digits

In C++, there are different types of variables (defined with different keywords), for example:

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 double - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 string - stores text, such as "Hello World". String values are surrounded by double quotes
 bool - stores values with two states: true or false

Example:

int myNum = 5; // Integer (whole number without decimals)


double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)

Hello world program:

#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}

Program without using namespace:

#include <iostream>
int main() {
std :: cout << "Hello World!";
return 0;
}

The std is a short form of standard, the std namespace contains the built-in classes and declared functions.

Namespaces are regions in a program logically separated from the rest. They are necessary if you want
more than one function with the same name. You can declare two different namespaces for these
functions and call them by referencing their corresponding namespace.

It is similar to referencing the second names when two people have the same first name. So namespace
tells the compiler which of the two identically named functions to use.

What is the C++ Namespace?

Namespace in C++ is the declarative part where the scope of identifiers like functions, the name of
types, classes, variables, etc., are declared. The code generally has multiple libraries, and the namespace
helps in avoiding the ambiguity that may occur when two identifiers have the same name.

For example, suppose you have two functions named calculate (), and both are performing different tasks.
One calculate () function is doing the multiplication, and another is doing the addition. So in this case, to
avoid ambiguity, you will declare both the functions in two different namespaces. These namespaces will
differentiate both the functions and also provide information regarding both the functions.

Definition:

You can define a namespace as follows:

namespace namespace_name

int a, b;

Important points to consider while declaring a namespace:

 You can only define them in a global scope.


 It is only present in C++ and not in C.
 To access a class inside a namespace, you can use namespacename::classname.
Standard Namespace:

The std is a short form of standard, the std namespace contains the built-in classes and declared functions.

You can find all the standard types and functions in the C++ "std" namespace. There are also several
namespaces inside "std."

Example:

Here std is used in front of cin and cout along with scope resolution operator, which indicates that the
object cin and cout are defined inside the namespace whose name is std.

The std is the standard library, and both cin and cout are defined inside this scope.

Now, learn how to define C++ Namespace.

How Do You Define Namespace in C++?

To define a namespace, first, the namespace keyword is written in the beginning and then the name of the
namespace, and inside the brackets, there are declarations.

Syntax:
Example:

Here, the name of the namespace is the column, and the variable named data is declared as its member.

Now, understand how to access C++ namespace members.

How to Access Namespace Members?

As you have understood how to define your own namespace, you will now learn how to access the
contents of this namespace.

To access the namespace members, you can use the name of the namespace and the member name, along
with the scope resolution operator.

Syntax:

Example:

Here data variable whose value is 20 is declared in the namespace and another variable data having value
140.57 is declared in the main function. To print both the variables we have to put the namespace name in
front of the data variable having value 20 i.e column::data, otherwise both data variables will print
140.57.

So to print the value of a namespace member, we have to write a namespace with its scope, which will
avoid the name clash.
Input Output function:

cout is pronounced "see-out". Used for output, and uses the insertion operator (<<)

cin is pronounced "see-in". Used for input, and uses the extraction operator (>>)

Example:

int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;

User Input Strings:


string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;

Output:

Type your full name: John Doe


Your name is: John

However, cin considers a space (whitespace, tabs, etc) as a terminating character, which means that it can
only store a single word (even if you type many words).

From the example above, you would expect the program to print "John Doe", but it only prints "John".

That's why, when working with strings, we often use the getline() function to read a line of text. It
takes cin as the first parameter, and the string variable as second:

string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;

Output:

Type your full name: John Doe


Your name is: John Doe

The foreach Loop:

Syntax:
for (type variableName : arrayName) {
// code block to be executed
}
Example:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}

Note: The for-each loop was introduced in C++ version 11 (2011).

Example:
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};

// Loop through strings


for (string car : cars) {
cout << car << "\n";
}

Function:

Default Parameter Value:

You can also use a default parameter value, by using the equals sign (=).

If we call the function without an argument, it uses the default value ("Norway"):

Example:
void myFunction(string country = "Norway") {
cout << country << "\n";
}

int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}

// Sweden
// India
// Norway
// USA

A parameter with a default value, is often known as an "optional parameter". From the example
above, country is an optional parameter and "Norway" is the default value.

OOP (Object oriented programming):


There are some basic concepts that act as the building blocks of OOPs

 Class
 Object
 Encapsulation
 Abstraction
 Polymorphism
 Inheritance

Characteristics of an Object-Oriented Programming Language:

Class:

Collection of objects is called class. It is a logical entity.


A class is like a blueprint for an object. It provides template for creating objects. No memory is
allocated for class.

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

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.

Syntax:

Object:
Object means a real word entity such as pen, chair, table etc.
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.

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;

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()

Difference between Classes and Objects:

Class Object

Class is the blueprint of an object. It is used to


An object is an instance of the class.
create objects.

Memory is allocated as soon as an object is


No memory is allocated when a class is declared.
created.

An object is a real-world entity such as a book,


A class is a group of similar objects.
car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.

C++ program to illustrate how create a simple class and object:

#include <iostream>
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 = "Xyz";
person1.age = 30;

// Call the introduce member method


person1.introduce();

return 0;
}

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

Data abstraction refers to providing only essential information to the outside world and hiding their
background details.

Data abstraction is a programming (and design) technique that relies on the separation of interface and
implementation.

Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the
volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know
its internal details, that is, you do not know how it receives signals over the air or through a cable, how it
translates them, and finally displays them on the screen.

Thus, we can say a television clearly separates its internal implementation from its external interface and
you can play with its interfaces like the power button, channel changer, and volume control without
having any knowledge of its internals.

In C++, classes provide great level of data abstraction. They provide sufficient public methods to the
outside world to play with the functionality of the object and to manipulate object data, i.e., state without
actually knowing how class has been implemented internally.
For example, your program can make a call to the sort () function without knowing what algorithm the
function actually uses to sort the given values. In fact, the underlying implementation of the sorting
functionality could change between releases of the library, and as long as the interface stays the same,
your function call will still work.

In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of
class ostream to stream data to standard output like this –

Example:

#include <iostream>

using namespace std;

class Adder {

public:

// constructor

Adder(int i = 0) {

total = i;

// interface to outside world

void addNum(int number) {

total += number;

// interface to outside world

int getTotal() {

return total;

};

private:

// hidden data from outside world

int total;

};

int main() {
Adder a;

a.addNum(10);

a.addNum(20);

a.addNum(30);

cout << "Total " << a.getTotal() <<endl;

return 0;

Output:

Total 60

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 the process of tying together data and the functions that work with it in object-oriented
programming.

Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which variables but
object-oriented programming provides you framework to place the data and the relevant functions
together in the same object.

Example:

#include<iostream>

using namespace std;

class Box {

public:

Box(int l=5,int b=8,int h=4) {

length=l;

breadth=b;

height=h;

}
double getVolume(void) {

return length * breadth * height;

private:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

int main()

Box b1;

int area = b1.getVolume();

cout<<area;

Output:

160

Access Specifiers :
Access specifiers define how the members (attributes and methods) of a class can be accessed.

In C++, there are three access specifiers:

 public - members are accessible from outside the class


 private - members cannot be accessed (or viewed) from outside the class
 protected - members cannot be accessed from outside the class, however, they can be accessed in
inherited classes. You will learn more about Inheritance later.

Constructors:
 A constructor in C++ is a special method that is automatically called when an object of a class is
created.
 It helps to initialize the object of a class.
 It is used to allocate the memory to an object of the class.
 It can be defined manually with arguments or without arguments.
 There can be many constructors in a class.
Characteristics of Constructors in C++:

 The name of the constructor is the same as its class name.

 Constructors are mostly declared in the public section of the class though they can be declared in
the private section of the class.

 Constructors do not return values; hence they do not have a return type.

 A constructor gets called automatically when we create the object of the class.

To create a constructor, use the same name as the class, followed by parentheses ():

Syntax:

ClassName()
{
//Constructor's Body
}

Example:

#include<iostream>

using namespace std;

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}

Types of Constructors in C++:

1. Default Constructor:
Discussed above.

2. Parameterized Constructor:
Parameterized Constructors make it possible to pass arguments to constructors. Typically, these
arguments help initialize an object when it is created.

Syntax of Parameterized Constructor:


className (parameters...) {
// body
}

Example:

#include <iostream>
using namespace std;

class Point {
private:
int x, y;

public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}

int getX() { return x; }


int getY() { return y; }
};

int main()
{
// Constructor called
Point p1(10, 15);

// Access values assigned by constructor


cout << "p1.x = " << p1.getX()
<< ", p1.y = " << p1.getY();

return 0;
}

Output:

p1.x = 10, p1.y = 15

Default Arguments with C++ Parameterized Constructor:


Just like normal functions, we can also define default values for the arguments of parameterized
constructors.

3. Copy Constructor:

A copy constructor is a member function that initializes an object using another object of the same class.

Syntax of Copy Constructor:

Copy constructor takes a reference to an object of the same class as an argument.


ClassName (ClassName &obj)
{
// body_containing_logic
}

Example:

#include <iostream>
using namespace std;

// Create a demo class


class A {
public:
int x;

A(){};

// Copy Constructor definition


A (A &t) {
x = t.x;
cout << "Calling copy constructor" << endl;
}
};

int main() {

// Creating an a1 object
A a1;
a1.x = 10;
cout << "a1's x = " << a1.x << endl;

// Creating another object using a1 Copy Constructor Calling


A a2(a1);
cout << "a2's x = " << a2.x;

return 0;
}

Output:

a1's x = 10
Calling copy constructor
a2's x = 10
Destructors in C++:

Characteristics of a Destructor:

 A destructor is also a special member function like a constructor. Destructor destroys the
class objects created by the constructor.

 Destructor has the same name as their class name preceded by a tilde (~) symbol.

 It is not possible to define more than one destructor.

 The destructor is only one way to destroy the object created by the constructor. Hence,
destructor cannot be overloaded.

 It cannot be declared static or const.

 Destructor neither requires any argument nor returns any value.

 It is automatically called when an object goes out of scope.

 Destructor release memory space occupied by the objects created by the constructor.

 In destructor, objects are destroyed in the reverse of an object creation.

Example:
#include <iostream>
using namespace std;

class Test {
public:
// User-Defined Constructor
Test() { cout << "\n Constructor executed"; }

// User-Defined Destructor
~Test() { cout << "\nDestructor executed"; }
};
int main()
{
Test t;

return 0;
}

Inheritance:

Inheritance is a feature or a process in which, new classes are created from the existing classes. The new
class created is called “derived class” or “child class” and the existing class is known as the “base
class” or “parent class”. The derived class now is said to be inherited from the base class.

When we say derived class inherits the base class, it means that the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new features to its
own.
 Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.

 Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.

Why and When to Use Inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we create these classes
without inheritance, then we have to write all of these functions in each of the three classes as shown
below figure:

You can clearly see that the above process results in duplication of the same code 3 times. This increases
the chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create
a class Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle
class, then we can simply avoid the duplication of data and increase re-usability. Look at the below
diagram in which the three classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as we have
inherited the rest of the three classes from the base class (Vehicle).

Syntax of Inheritance in C++:

class derived_class_name : access-specifier base_class_name


{
// body ....
};

where,

 class: keyword to create a new class


 derived_class_name: name of the new class, which will inherit the base class

 access-specifier: Specifies the access mode which can be either of private, public or protected. If
neither is specified, private is taken as default.

 base-class-name: name of the base class.

is-a relationship:

Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is present between the
two classes.

Here are some examples:

 A car is a vehicle.

 Orange is a fruit.

 A surgeon is a doctor.

 A dog is an animal.

Modes of Inheritance in C++:

Mode of inheritance controls the access level of the inherited members of the base class in the
derived class. In C++, there are 3 modes of inheritance:

 Public Mode
 Protected Mode
 Private Mode

Public Inheritance Mode:

If we derive a subclass from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become protected in
the derived class.

Example:

class ABC : public XYZ {...} // public derivation

Protected Inheritance Mode:

If we derive a subclass from a Protected base class. Then both public members and protected
members of the base class will become protected in the derived class.

Example:

class ABC : protected XYZ {...} // protected derivation


Private Inheritance Mode:

If we derive a subclass from a Private base class. Then both public members and protected members
of the base class will become private in the derived class. They can only be accessed by the member
functions of the derived class.

Private mode is the default mode that is applied when we don‟t specify any mode.

Example:

class ABC : private XYZ {...} // private derivation


class ABC: XYZ {...} // private derivation by default

Examples of Modes of Inheritance:

Example 1: Program to show different kinds of Inheritance Modes and their Member Access Levels

class A {
public:
int x;

protected:
int y;

private:
int z;
};

class B : public A {
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

Example 1: C++ public Inheritance:

// C++ program to demonstrate the working of public inheritance

#include <iostream>
using namespace std;
class Base {
private:
int pvt = 1;

protected:
int prot = 2;

public:
int pub = 3;

// function to access private member


int getPVT() {
return pvt;
}
};

class PublicDerived : public Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}
};

int main() {
PublicDerived object1;
cout << "Private = " << object1.getPVT() << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.pub << endl;
return 0;
}

Output:

Private = 1
Protected = 2
Public = 3

Accessibility in public Inheritance:

Accessibility private members protected members public members

Base Class Yes Yes Yes

Derived Class No Yes Yes


Example 2: C++ protected Inheritance:
// C++ program to demonstrate the working of protected inheritance

#include <iostream>
using namespace std;

class Base {
private:
int pvt = 1;

protected:
int prot = 2;

public:
int pub = 3;

// function to access private member


int getPVT() {
return pvt;
}
};

class ProtectedDerived : protected Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}

// function to access public member from Base


int getPub() {
return pub;
}
};

int main() {
ProtectedDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}

Output

Private cannot be accessed.


Protected = 2
Public = 3
Accessibility in protected Inheritance:

private protected
Accessibility public members
members members

Base Class Yes Yes Yes

Derived Yes (inherited as protected


No Yes
Class variables)

Example 3: C++ private Inheritance


#include <iostream>
using namespace std;

class Base {
private:
int pvt = 1;

protected:
int prot = 2;

public:
int pub = 3;

// function to access private member


int getPVT() {
return pvt;
}
};

class PrivateDerived : private Base {


public:
// function to access protected member from Base
int getProt() {
return prot;
}

// function to access private member


int getPub() {
return pub;
}
};

int main() {
PrivateDerived object1;
cout << "Private cannot be accessed." << endl;
cout << "Protected = " << object1.getProt() << endl;
cout << "Public = " << object1.getPub() << endl;
return 0;
}
Output:

Private cannot be accessed.


Protected = 2
Public = 3

Accessibility in private Inheritance


private
Accessibility protected members public members
members

Base Class Yes Yes Yes

Derived Yes (inherited as Yes (inherited as


No
Class private variables) private variables)

Types of Inheritance in C++:

The inheritance can be classified on the basis of the relationship between the derived class and the base
class. In C++, we have 5 types of inheritances:

1. Single inheritance

2. Multilevel inheritance

3. Multiple inheritance

4. Hierarchical inheritance

5. Hybrid inheritance

1. Single Inheritance

In single inheritance, a class is allowed to inherit from only one class. i.e. one base class is inherited by
one derived class only.

Syntax

class subclass_name : access_mode base_class


{
// body of subclass
};

Example:
class A
{
... .. ...
};
class B: public A
{
... .. ...
};

Implementation:

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// sub class derived from a single base classes


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes
Car obj;
return 0;
}

Output

This is a Vehicle
This Vehicle is Car
2. Multiple Inheritance

Multiple Inherita nce is a feature of C++ where a class can inherit from more than one class. i.e
one subclass is inherited from more than one base class.

Syntax

class subclass_name : access_mode base_class1, access_mode base_class2, ....


{
// body of subclass
};

Here, the number of base classes will be separated by a comma („, „) and the access mode for every
base class must be specified and can be different.

Example:

class A
{
... .. ...
};
class B
{
... .. ...
};
class C: public A, public B
{
... ... ...
};

Implementation:

#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler() { cout << "This is a 4 Wheeler\n"; }
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes.
Car obj;
return 0;
}

Output:

This is a Vehicle
This is a 4 Wheeler
This 4 Wheeler Vehical is a Car

3. Multilevel Inheritance:

In this type of inheritance, a derived class is created from another derived class and that derived class
can be derived from a base class or any other derived class. There can be any number of levels.

Syntax

class derived_class1: access_specifier base_class


{
... .. ...
}
class derived_class2: access_specifier derived_class1
{
... .. ...
}
.....

Example:

class C
{
... .. ...
};
class B : public C
{
... .. ...
};
class A: public B
{
... ... ...
};

Implementation:

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub_class derived from class vehicle


class fourWheeler : public Vehicle {
public:
fourWheeler() { cout << "4 Wheeler Vehicles\n"; }
};

// sub class derived from the derived base class fourWheeler


class Car : public fourWheeler {
public:
Car() { cout << "This 4 Wheeler Vehical is a Car\n"; }
};

// main function
int main()
{
// Creating object of sub class will invoke the constructor of base classes.
Car obj;
return 0;
}

Output:

This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehical is a Car

4. Hierarchical Inheritance:

In this type of inheritance, more than one subclass is inherited from a single base class. i.e. more than one
derived class is created from a single base class.

Syntax:

class derived_class1: access_specifier base_class


{
... .. ...
}
class derived_class2: access_specifier base_class
{
... .. ...
}

Example:

class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Implementation
#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
public:
Car() { cout << "This Vehicle is Car\n"; }
};

// second sub class


class Bus : public Vehicle {
public:
Bus() { cout << "This Vehicle is Bus\n"; }
};

// main function
int main()
{
// Creating object of sub class will invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}

Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus

5. Hybrid Inheritance

Hybrid Inheritance is implemented by combining more than one type of inheritance. For example:
Combining Hierarchical inheritance and Multiple Inheritance will create hybrid inheritance in C++

There is no particular syntax of hybrid inheritance. We can just combine two of the above inheritance
types.

Example:

Below image shows one of the combinations of hierarchical and multiple inheritances:

class F
{
... .. ...
}
class G
{
... .. ...
}
class B : public F
{
... .. ...
}
class E : public F, public G
{
... .. ...
}
class A : public B {
... .. ...
}
class C : public B {
... .. ...
}
Implementation:

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};

// first sub class


class Car : public Vehicle {
public:
Car() { cout << "This Vehical is a Car\n"; }
};

// second sub class


class Bus : public Vehicle, public Fare {
public:
Bus() { cout << "This Vehicle is a Bus with Fare\n"; }
};

// main function
int main()
{
// Creating object of sub class will invoke the constructor of base class.
Bus obj2;
return 0;
}

Output:

This is a Vehicle
Fare of Vehicle
This Vehicle is a Bus with Fare

Note:
Order of constructor call for Multiple Inheritance:
For multiple inheritance order of constructor call is, the base class‟s constructors are called in the order
of inheritance and then the derived class‟s constructor.

Destructors in C++ are called in the opposite order of that of Constructors.


C++ Polymorphism:
The word “polymorphism” means having many forms.

A man at the same time is a father, a husband, and an employee. So the same person exhibits different
behavior in different situations. This is called polymorphism. Polymorphism is considered one of the
important features of Object-Oriented Programming.

Types of Polymorphism:

 Compile-time Polymorphism
 Runtime Polymorphism

1. Compile-Time Polymorphism:

This type of polymorphism is achieved by function overloading or operator overloading.

A. Function Overloading:

When there are multiple functions with the same name but different parameters, then the functions are said
to be overloaded, hence this is known as Function Overloading. Functions can be overloaded by changing
the number of arguments or/and changing the type of arguments and changing order of arguments. In
simple terms, it is a feature of object-oriented programming providing many functions that have the same
name but distinct parameters when numerous tasks are listed under one function name. There are certain
Rules of Function Overloading that should be followed while overloading a function.

Below is the C++ program to show function overloading or compile-time polymorphism:

// C++ program to demonstrate function overloading or Compile-time Polymorphism


#include <iostream>
using namespace std;
class A{
public:
void func(int x)
{
cout << "value of x is " << x << endl;
}
void func(double x)
{
cout << "value of x is " << x << endl;
}
void func(double x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
void func(int x, double y)
{
cout << "value of x and y is " << x << ", " << y<< endl;
}
};
int main()
{
A obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85.89, 64);
obj1.func(10, 20.78);
return 0;
}

Output:

value of x is 7
value of x is 9.132
value of x and y is 85.89, 64
value of x and y is 10, 20.78

Explanation: In the above example, a single function named function func() acts differently in three
different situations, which is a property of polymorphism.

B. Operator Overloading:

C++ has the ability to provide the operators with a special meaning for a data type, this ability is known
as operator overloading. For example, we can make use of the addition operator (+) for string class to
concatenate two strings. We know that the task of this operator is to add two operands. So a single
operator „+‟, when placed between integer operands, adds them and when placed between string
operands, concatenates them.

Below is the C++ program to demonstrate operator overloading:

// C++ program to demonstrate Operator Overloading or Compile-Time Polymorphism


#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects
Complex operator+ (Complex obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2; // c3 = c1.add(c2);
c3.print();
}

Output:

12 + i9

Explanation: In the above example, the operator „+‟ is overloaded. Usually, this operator is used to add
two numbers (integers or floating point numbers), but here the operator is made to perform the addition of
two imaginary or complex numbers.

2. Runtime Polymorphism:

This type of polymorphism is achieved by Function Overriding. Late binding and dynamic polymorphism
are other names for runtime polymorphism. The function call is resolved at runtime in runtime
polymorphism. In contrast, with compile time polymorphism, the compiler determines which function call
to bind to the object after deducing it at runtime.

A. Function Overriding:

Function Overriding occurs when a derived class has a definition for one of the member functions of the
base class. That base function is said to be overridden.
Function overriding Explanation

Runtime Polymorphism with Data Members:

Runtime Polymorphism cannot be achieved by data members in C++. Let‟s see an example where we are
accessing the field by reference variable of parent class which refers to the instance of the derived class.

Example:

// C++ program for function overriding with data members

#include <iostream>

using namespace std;

// base class declaration.

class Animal {

public:

string color = "Black";

void display()

cout<<"Base="<<color<<endl;

};

// inheriting Animal class.

class Dog : public Animal {

public:
string color = "Grey";

void display()

cout<<"Derived="<<color<<endl;

};

// Driver code

int main(void)

Dog d; // accessing the field by reference/ variable which refers to derived

cout << d.color<<endl;

d.display();

Output:

Grey
Derived=grey

We can see that the parent class reference will always refer to the data member of the parent class.
Child class object refers its member first if it is available otherwise refers parent class members.

B. Virtual Function:
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-
defined (Overridden) in the derived class.

Some Key Points about Virtual Functions:


 Virtual functions are Dynamic in nature.
 They are defined by inserting the keyword “virtual” inside a base class and are always declared with a
base class and overridden in a child class
 A virtual function is called during Runtime

Example:

Below is the C++ program to demonstrate virtual function:

Virtual function:

#include <iostream>

using namespace std;

class Animal {

public:
string color = "Black";

virtual void display()

cout<<"Base="<<color<<endl;

} };

class Dog : public Animal {

public:

string color = "Grey";

void display()

cout<<"Derived="<<color<<endl;

} };

int main()

Animal *a;

Dog d;

a=&d;

// Animal a;

a->display();

d.display();

Rules for virtual functions:

1. They cannot be static

2. They are accessed by object pointers

3. Virtual function can be a friend of another class

4. A virtual function in base class might not be used

If a virtual function is defined in a base class, there is no necessity of redefining it in the derived class.

Friend Class:
A friend class can access private and protected members of other classes in which it is declared as a
friend. It is sometimes useful to allow a particular class to access private and protected members of other
classes. For example, a LinkedList class may be allowed to access private members of Node.
We can declare a friend class in C++ by using the friend keyword.

Syntax:

friend class class_name; // declared in the base class

Example:

#include<iostream>

using namespace std;

class A

private:

int x;

protected:

int y;

public:

A(){

x=34;

y=90;

friend class B;

};

class B{

public:

void display(A a){

cout<<"x="<<a.x<<endl<<"y="<<a.y<<endl;

};

int main(){

A a;

B b;

b.display(a);

}
Output:

x=34

y=90

Friend function:
Like a friend class, a friend function can be granted special access to private and protected members of a
class in C++. They are not the member functions of the class but can access and manipulate the private and
protected members of that class for they are declared as friends.
A friend function can be:

1. A global function
2. A member function of another class

Friend Function in C++

Syntax:

friend return_type function_name (arguments); // for a global function


or
friend return_type class_name::function_name (arguments); // for a

member function of another class

Properties of friend function:


1. Not in the scope of class, so, it cannot be called from the object of that calss.
2. Can be invoked without the help of any object
3. Usually contains objects as arguments
4. Can be declared inside public or private section of the class
5. It cannot access the members directly by their names and need object_name.member_name to
access any member.

1. Global Function as Friend Function:

#include<iostream>
using namespace std;

class A

private:

int x;

protected:

int y;

public:

A(){

x=34;

y=90;

friend void display(A);

};

// friend function definition

void display(A a)

cout << "X=" << a.x << endl;

cout << "Y=" << a.y;

int main(){

A a;

display(a);

Output:

x=34

y=90

Example:

#include <iostream>

using namespace std;


class B; // forward declarartion.

class A

int x;

public:

void setdata(int i)

x=i;

friend void min(A,B); // friend function.

};

class B

int y;

public:

void setdata(int i)

y=i;

friend void min(A,B); // friend function

};

void min(A a, B b)

if(a.x<=b.y)

cout << a.x << endl;

else

cout << b.y << endl;

int main()

{
A a;

B b;

a.setdata(10);

b.setdata(20);

min(a,b);

return 0;

Output:

10

2. Member Function of another Class as Friend Function:


We can also declare a member function of another class as a friend function in C++. The following
example demonstrates how to use a member function of another class as a friend function in C++:
Example:

#include<iostream>

using namespace std;

class A;

class B {

public:

int sum(A , A); };

class A {

int a;

friend int B ::sum(A, A);

public:

void setNumber(int n1)

a = n1;

};

int B ::sum(A o1, A o2) {

return (o1.a + o2.a); }

int main() {
A o1, o2;

o1.setNumber(1);

o2.setNumber(5);

B b;

int res = b.sum(o1, o2);

cout << "The sum is " << res << endl;

return 0; }

Output:

The sum is 6

Abstract Class:
An abstract base class has at least one pure virtual function.

Sometimes implementation of all functions cannot be provided in a base class because we don‟t know the
implementation. Such a class is called an abstract class.

For example, let Shape be a base class. We cannot provide the implementation of function draw() in
Shape, but we know every derived class must have an implementation of draw(). Similarly, an Animal
class doesn‟t have the implementation of move() (assuming that all animals move), but all animals must
know how to move.

We cannot create objects of abstract classes.

A pure virtual function (or abstract function) in C++ is a virtual function for which we can have an
implementation, But we must override that function in the derived class, otherwise, the derived class will
also become an abstract class. A pure virtual function is declared by assigning 0 in the declaration.

// An abstract class
class Test {
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};

Example:
#include <iostream>

using namespace std;

class Base {

public:

// pure virtual function


virtual void fun()=0;

};

class Derived : public Base {

public:

// implementation of the pure virtual function

void fun() { cout << "fun() called"; }

};

int main()

Derived d;

d.fun();

return 0;

Output:

fun() called

Note:

An abstract class in C++ can also be defined using struct keyword.

Example:

struct shapeClass
{
virtual void Draw()=0;
}

Properties of abstract class:

1. Abstract classes cannot be instantiated directly.


2. An abstract class must have at least one abstract method (pure virtual function).
3. An abstract class includes final methods.
4. An abstract class may also include non-abstract (concrete methods) methods.
5. An abstract class can consist of constructors and static methods.

What is a reference variable in C++?

Reference variable is an alternate name of already existing variable. It cannot be changed to refer another
variable and should be initialized at the time of declaration and cannot be NULL.

The operator „&‟ is used to declare reference variable.

The following is the syntax of reference variable.


datatype variable_name; // variable declaration
datatype & refer_var = variable_name; // reference variable

Here,

datatype − The datatype of variable like int, char, float etc.

variable_name − This is the name of variable given by user.

refer_var − The name of reference variable.

The following is an example of reference variable.

Example:

#include <iostream>
using namespace std;
int main() {
int a = 8;
int &b = a;
cout << "The variable a : " << a;
cout << "\nThe reference variable r : " << b;
b++;
cout << "The variable a : " << a;
cout << "\nThe reference variable: " << b;
return 0;
}

Output:

The variable a : 8
The reference variable: 8
The variable a : 9
The reference variable: 9

Instance Variable:

An "instance variable" in C++ is a variable declared within a class, outside of any methods, which means
each object created from that class will have its own separate copy of the variable, allowing for unique
data storage within each object; essentially, it defines the state of an object within a class.

#include <iostream>

using namespace std;

class Person {

public:

string name;

int age;

};
int main() {

Person person1;

person1.name = "John";

person1.age = 30;

Person person2;

person2.name = "Jane";

person2.age = 25;

return 0;

Explanation:
 In this example, "name" and "age" are considered instance variables within the "Person" class.
 When you create objects "person1" and "person2", each will have its own separate "name" and "age"
values.

Static Keyword in C++:

When a static keyword is used, variables, data members, and functions cannot be modified again.

It is allocated for the lifetime of the program. Static functions can be called directly by using a class
name.

Key Points of Static Variables:

Static variables are variables that are defined using static keywords, which consist of special behavior
compared to regular variables. Here we will see its key points.

1. Static variables are initialized to zero when first object created.


2. Static variables can be defined inside or outside the function.
3. The static variables are alive (Life time) till the execution of the program.

Syntax:

Here is the syntax of static keyword in C++ language,

static datatype variable_name; // Static variable


static return_type function_name() { // Static functions
...
}

 Here, datatype − The datatype of variables like int, char, float, etc.
 variable_name − This is the name of the variable given by the user.
 value − Any value to initialize the variable. By default, it is zero.
 return_type − The datatype of the function to return the value.
 function_name − Any name to the function.

Example:

#include <iostream>

using namespace std;

class Box {

public:

static int objectCount;

// Constructor definition

Box() {

cout <<"Constructor called." << endl;

// Increase every time object is created

objectCount++;

static int getCount() {

return objectCount;

};

// Initialize static member of class Box

int Box::objectCount = 0;

int main() {

cout << "Inital Stage Count: " << Box::getCount() << endl;

cout << "Initial Stage Count: " << Box::objectCount << endl;

Box b1,b2;

// Print total number of objects after creating object.

cout << "Final Stage Count: " << Box::getCount() << endl;

cout << "Final Stage Count: " << Box::objectCount << endl;

return 0;

}
Static object: There is no such thing as a static class in C++. The closest approximation is a class that
only contains static data members and static methods.

Static class means it contains all static data members and member functions.

#include<iostream>

using namespace std;

class A{

public:

A(){

cout<<"Constructor called"<<endl;

~A(){

cout<<"Destructor called"<<endl;

};

int main(){

static A a;

cout<<"End of program"<<endl;

return 0;

Output:

Constructor called

End of program

Destructor called

You might also like