0% found this document useful (0 votes)
34 views42 pages

OOP Notes

The document provides an overview of Object-Oriented Programming (OOP) and its principles, contrasting it with procedural programming. It covers key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with examples of functions and constructors. Additionally, it discusses access specifiers, constant variables, and the importance of functions in code organization and reusability.

Uploaded by

minarajpoot138
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views42 pages

OOP Notes

The document provides an overview of Object-Oriented Programming (OOP) and its principles, contrasting it with procedural programming. It covers key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction, along with examples of functions and constructors. Additionally, it discusses access specifiers, constant variables, and the importance of functions in code organization and reusability.

Uploaded by

minarajpoot138
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Object Oriented Programming

➾ Procedural Language
● C
● Fortran

➾ OOP
● Java
● C++
● Dart
● Swift
● C#
● Kotlin
● PHP

Procedure Language
➾ Focus on procedure
➾ Main Component is divided into smaller which are different functions/sectors
➾ Structural procedural language, the main problem is data is scattered and not secure
➾ Data movement around the function i.e, Top-down approach
➾ Also called Structural programming language

Object Oriented Programming


➾ Big program divided into smaller program
➾ More Secure → because every data has a layer of object
➾ Data has more importance
➾ Data movement around the system is not possible (Functions can access each other i.e, Function
movement is possible)
➾ The name of this technique is Bottom-up approach
Introduction to Object-Oriented Programming
➾ It is a way to program i.e, a technique, and is not a programming language

Definition
OOP is a programming technique in which programs are written on the base of object.
● OOP is an approach
● OOP is a way of working
● OOP is a design
● OOP is a design pattern
● OOP is not a programming language
● OOP is a name of the structure
● OOP is a architecture

What is object?
● An object is the collection of data and functions.
● Object represents a person, place or thing in the real world
● In OOP, data and all the possible functions on a data are grouped together

Pillars of OOp
1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation

→ Inheritance
This allows a new class (subclass/derived class) to inherit properties and behaviours from an existing
class (base class/parent class). It promotes code reuse and establishes a relationship between classes.

Function
● A function is a block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● Functions are used to perform certain actions, and they are important for reusing code:
● Define the code once, and use it many times.
● used when we have to do specific work

function is a self-contained block of code that performs a specific task. Functions allow you to break
down a program into smaller, modular pieces, making the code more organized and easier to manage.

Function Benefits:
● Re useability
● Code organization
Types of Functions:
There are two types of functions
1. Pre Defined Function
2. User defined functions

Pre Defined Function

C++ provides some predefined functions, such as main(), which is used to execute code. But you can
also create your own functions to perform certain actions.

→ Function name should be descriptive (to explain/understand easily)


→ Always use camel case (single upper case letter between lower case letter)

User Defined Function


→ Function Name
→ Parentheses
→ Function body
→ Return Type (optional)
→ Parameters (optional)

Function depends upon


There are three major components of a function.
→ Function definition
→ Function calling
→ Function prototype

Function definition:
Writing out the instructions or steps that a function will perform, If function is defined then function
prototype is not necessary

Function Calling:
Function calling is like telling the computer to execute the instructions (code) you wrote in a function
definition.

Function prototype:

—--------------------------------------------------------------------------------------------------------------------------------
#include <iostream>

// Create a function
void myFunction() {
std::cout << "I just got executed!\n"; // Use std::cout for output
}

int main() {
myFunction(); // Call the function
myFunction();
myFunction();
return 0;
}

—------------------------------------------------------------------------------------------------------------------------------
Returntype Example

Note:
1. The Line after the return value is not executed
2. We cannot return multiple values in a single statement
3. Any statement after the return keyword will not be executed.
4. Single value can be returned i.e, constant , variable

Example 1:

#include <iostream>
using namespace std;

int subjects(int n1, int n2, int n3, int n4)


{
int sum;
sum = n1+n2+n3+n4;
return sum ;

main ()
{
int oop, se, cn, de;
int result, average;
cout <<"Enter the number of OOP "<<endl;
cin >> oop;

cout <<"Enter the number of SE "<<endl;


cin >> se;

cout <<"Enter the number of cn "<<endl;


cin >> cn;

cout <<"Enter the number of de "<<endl;


cin >> de;

result = subjects (oop, se, cn, de);


average = result /4;
cout <<"Your Total Marks of all subjects is: "<<result<<endl;
cout <<"Your average of all subjects is: "<<average<<endl;

}
—----------------------------------------------------------------------------------------------------------------------
Function Example

#include <iostream>
using namespace std;

int addition(int n1, int n2, int n3)


{
int sum;
sum = n1 + n2 + n3;
cout<<"The Sum of given numbers is: "<<sum<<endl;
}

int subtraction(int n1, int n2, int n3)


{
int sum;
sum = n1 - n2 - n3;
cout<<"The subtraction of given numbers is: "<<sum<<endl;
}

int multiplication(int n1, int n2, int n3)


{
int sum;
sum = n1 * n2 * n3;
cout<<"The multiplication of given numbers is: "<<sum<<endl;
}

int division(int n1, int n2, int n3)


{
int sum;
sum = n1 / n2 / n3;
cout<<"The division of given numbers is: "<<sum<<endl;
}

int main()
{
int a,b,c;

cout << "Enter Any Number: ";


cin >> a;
cout << "Enter Another Number: ";
cin >> b;
cout << "Enter Some Another Number: ";
cin >> c;

addition(a, b, c);

subtraction(a, b, c);

multiplication (a, b, c);

division(a, b, c);
}
—------------------------------------------------------------------------------------------------

Prototype Example

#include <iostream>
using namespace std;
int addition(int n1, int n2, int n3);
int subtraction(int n1, int n2, int n3);
int multiplication(int n1, int n2, int n3);
int division(int n1, int n2, int n3);

int main()
{
int a;
int b;
int c;

cout << "Enter Any Number: ";


cin >> a;
cout << "Enter Another Number: ";
cin >> b;
cout << "Enter Some Another Number: ";
cin >> c;
addition(a, b, c);
subtraction(a, b, c);
multiplication (a, b, c);
division(a, b, c);
}

int addition(int n1, int n2, int n3)


{
int sum;
sum = n1 + n2 + n3;
cout<<"The Sum of given numbers is: "<<sum<<endl;
}

int subtraction(int n1, int n2, int n3)


{
int sum;
sum = n1 - n2 - n3;
cout<<"The subtraction of given numbers is: "<<sum<<endl;
}

int multiplication(int n1, int n2, int n3)


{
int sum;
sum = n1 * n2 * n3;
cout<<"The multiplication of given numbers is: "<<sum<<endl;
}

int division(int n1, int n2, int n3)


{
int sum;
sum = n1 / n2 / n3;
cout<<"The division of given numbers is: "<<sum<<endl;
}

—---------------------------------------------------------------------------------------------------------

Abstraction and Classes

Classes:
Capture only those details about an object that are relevant to the current perspective to the problem
Class:
A class is a grouping of objects that share similar characteristics and attributes.
● All the objects of the same characteristics and attributes we have combine all the attributes and
make sketch are prototypes or map
● A class is an entity that determines how an object wil behave and what the object will contain.
● In other words, it is a blueprint or a set of instructions to build a specific type of object.
● Class is major component of OOP
● Class provides most advance feature

Rules:
1. Class Name always in upper camel case
2. Class name should not be reversed keyword like void
3. Class always represent specific type of group
4. No digits, no space, no symbol. i.e, same rule will be used that are followed while writing
variables

Class depends upon


There are three major components of a class.
→ Class Name
→ Attributes/Data Members
→ Method/Function Members

Example 1:
—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class Teacher
{
public:
void teach()
{
cout << "Professor Zubair" << endl;
}
};

int main ()
{
Teacher t1;
t1.teach();
return 0; // Added return statement for completeness
}

—---------------------------------------------------------------------------------------------------

Example 2:
—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class Calculator
{
public:
int add (int a, int b) {
int sum = a+b;
return sum;
}
};
int main () {
int a,b,c, result;
cout<<"Enter Any Number "<<endl;
cin>>a;
cout<<"Enter Second Number "<<endl;
cin>>b;

Calculator c1;
result = c1.add(a,b);

cout<<"The Sum of both Numbers is: " <<result<<endl;


return 0;

}
—---------------------------------------------------------------------------------------------------

Access Specifiers
→ used to set availability of programs, define Boundary
There are three types of specifiers
1. Public
2. Private
3. Protected

Note: Always use a colon ‘‘:’’ at the end of access specifiers.

Public:
● Public means all class members can access it
● Function members are mostly written with Public
● Public with function members means they are accessible outside the class

Private:
● Fields/properties or Attributes are always written with Private
● Data members in private are accessible only within/inside the class
● Programs are by-default private in C++

Protected:
● It is like private
● It is used in class relationships or inheritance
● Both classes will access the properties, in case of relation of two classes

—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class AccessSpecifiers {
private:
int f;
public:
void getInfo() {
cout << "Enter Any Number: " << endl;
cin >> f;
}

void showInfo() {
cout << "Show: " << f << endl;
}
};

int main() {
AccessSpecifiers a;
a.getInfo();
a.showInfo();
return 0;
}
—---------------------------------------------------------------------------------------------------
Constructor
● constructor is used to initialize the properties of the class.
● constructor is the special function
● constructor works same as a function but it has no return type
● constructor name are the same as the name of class
● constructor is called automatically when object is created
● constructor has no manual calling as the function

—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;
class Text { //class
public: //access specifiers
Text() { //constructor
cout<<"Welcome to constructor "<<endl;
}
};
int main () {
Text t1;

}
—---------------------------------------------------------------------------------------------------

Destructor
● When an object is destroyed a special member of the class is executed automatically, this
member function is called destructor
● It also has same name as class name
● “~” Tilde is used before the destructor name

Example

#include <iostream>
using namespace std;

class Test {
public:
Test() {
cout << "Constructor executed"<<endl;
}

~Test() {
cout << "Destructor executed"<<endl;
}
};
int main() {
Test t;

return 0;
}
Constructor Overloading
● When we define more than one constructor in one class is called constructor overloading.
● When we define more than one constructor, Each constructor is defined with different set of
parameters.
● constructor overloading use to intilize in different values to object
● When a program that use constructor overloading, C++ compiler check the number of
parameters, check their order and datatype
● When an object of class is created corresponding the constructor that match the number of
parameter of the object function is executed
● We cannot use the same number of datatypes in two constructor

Example

#include<iostream>
using namespace std;
class Message {
private:
int a,b,c;
public:
Message() {
cout<<"My name is Faisal" <<endl;
}
Message( int c, int d) {
a=c;
b=d;
cout<<"sum of two values:" << a + b <<endl;
}
Message(int e, int f, int g) {
a=e;
b=f;
c=g;
cout<<"sum of three values:"<< a + b + c <<endl;
}
};
int main() {
Message M;
Message M2(3,6);
Message M3(4,5,6);
}
Copy Constructor
A type of constructor that is used to initialize an object with another object of the same type is known as
copy constructor

—---------------------------------------------------------------------------------------------------
Example

#include <iostream>
using namespace std;

class Student {
private:
char Name [40];
int roll_number, marks ;
public:
getInfo () {
cout<<"Enter The Name of the student "<<endl;
cin.getline(Name, 40);
cout<<"Enter the Roll Number of the student "<<endl;
cin>>roll_number;
cout<<"Enter The marks of the student"<<endl;
cin >>marks;
}
putInfo () {
cout<<"Name of student is: "<<Name<<endl;
cout<<"Roll Number of student is: "<<roll_number<<endl;
cout<<"Marks of student is: "<<marks<<endl;

}
};

int main () {
Student s;
s.getInfo ();
s.putInfo();

system ("pause");
Student s1;
s1=s;
s1.putInfo ();

return 0;
}

Constant Variable
1. Constant is something that cannot be changed
2. In C & C++, we use the keyword constant with element, which value cannot be changed
3. Constant keyword is used in many contexts
● Constant Data members
● Constant Function-members
● Constant Objects
4. If you make any variable as a constant, with a constant keyword, its value can’t be changed
5. Also the constant variable must be initialized when it is declared

Constant Object
1. We declare the object as a constant using the “const” keyword. By doing this, the properties of
an object once initialized, cannot be changed
2. Const → keyword is used before the class name while making an object

—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

class Test {
public:
string FName;
string LName;
Test(string Fn, string Ln) {
FName = Fn;
LName = Ln;
}
};

int main() {
Test T("MUhammad", "Faisal");

// Displaying the value of the FName member variable


cout << "Value of FName: " << T.FName << endl;

// Correcting the assignment of a new value to FName


T.FName = "Ali";

// Displaying the updated value of the FName member variable


cout << "Updated value of FName: " << T.FName << endl;

return 0;
}
—---------------------------------------------------------------------------------------------------
Note: Object is not a const variable so “Muhammad” and “Faisal” both can be assigned to the single
object

main() {
const Test T("MUhammad", "Faisal");
cout << "First Name is: " << T.FName << endl;
cout << "Last Name is: " << T.FName << endl;
}
—---------------------------------------------------------------------------------------------------

Constant Function Members


1. Const Keyword is used after the name of function
2. We have to make constant object to access constant function member

—---------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

class Myclass{
public:
int x;
void getInfo() const{
cout<<"Enter Any Number "<<endl;
cin>>x;
}
void putInfo (){
cout<<"The Value of X is: "<<x<<endl;
}

};
int main ()
{
const Myclass T;
T.getInfo ();
T.putInfo();
}

Note: In this case only first function can access the object. If we have to access both simple & constant
function then we will make two objects i,e sample of constant object
—---------------------------------------------------------------------------------------------------

Note: if the properties of the class and parameters of class are same than we can use the keyword
this-> with properties of the constructor

Note: To take the full name from the user with space, user can use cin.getline (Name, 40);

Note: For clear screen you can use system("cls");

Note: To take a Pause during execution, you can use system("pause");


Separate classes in different Files/locations

In C++, we can organize your code by separating classes into different files or locations. This practice is
known as modularization or organizing code into modules. It involves dividing the code into smaller,
manageable pieces, each containing related functionalities. Here's how you can achieve this:

---------------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------------
Inheritance

1. Major pillar of OOP.


2. The main purpose is CODE REUSE-ABILITY.
3. It is the relationship between Classes.

Definition of Inheritance:

Inheritance is the capability of one class to get the characteristics of another class. Inheritance is a
relationship between classes.

TYPES OF CLASSES
● Parent Class
● Child Class

Parent Class:
→ Also called Base class or Superclass.
→ Parent class is the class whose properties are inherited to another class.
OR
→ It is the class from which other classes inherit/acquire the properties.
● Parent class holds the common properties, attributes or characteristics.
i.e. Common data members are always in the parent class.
● Parent class holds common methods or fields.
i.e. Common function members are always in the parent class.

Child Class:
1. Also called Derive class or Subclass.
2. Child class is the class which inherits the properties of another class i.e. of parent class.
3. Child class holds Specific data members and function members.
i.e. it has its own specific properties, attributes or characteristics and its own specific fields or
methods.
{Here, common data and function members (M1&M2) of parent class i.e. Class A are being reused in
child class and also the child class i.e. Class B is holding its specific data/function member(M3).}

4. When we inherit an existing class, all of its data and function members appear in new class,
hence the code is being reused.
→ The new class (Child class) access these properties i.e. data and function members by making
object.
5. All the members of a class except “Private” can be inherited.
→ It means that if we declare some members of a class using an access specifier of private, then
these members can not be inherited in the child class.

ADVANTAGES OF INHERITANCE:
1. Code reusability.
2. It saves time and effort.
3. Increases program’s structure and reliability.

Syntax of Code:
class A{
data members;
function members;
};
Class B: public A {
specific datamembers;
specific memberfunctions;
};
int main( ){
B obj; // here B is child class and its object obj has access to all the data and
function members of Parent as well as child class
}

EXAMPLE 1:
Write a program in which a class is inherited from a parent class.

#include<iostream>
using namespace std;

class Animal{
public:
int legs = 4;
};
class Dog: public Animal {
public:
int tail = 1;
};
int main( ){
Dog d;
cout<<"Properties of parent class, legs = "<<d.legs<<endl;
cout<<"Functions of Child class, tail = "<<d.tail<<endl;
}

EXAMPLE 2:
Write a program in which two classes are inherited from a single parent class.

#include<iostream>
using namespace std;
class Animal{
public:
int legs=4;
int eyes=2;
int tail=1;

void drinkAnimal(){
cout<<"All animals drink water."<<endl;
}
void eatAnimal(){
cout<<"All animals do eat."<<endl;
}
};
class Dog:public Animal{
public:
string voice="Bark";
string eat="Meat";

void functionDog(){
cout<<"All dogs bark and eat meat."<<endl;
}
};
class Cat:public Animal{
public:
string voice="Meow";
string drink="Milk";

void functionCat(){
cout<<"All cats do meow and drink milk."<<endl;
}
void catInfo(){
cout<<"Number of legs in cat"<<legs<<endl;
cout<<"Number of eyes in cat"<<eyes<<endl;
cout<<"Number of tails in cat"<<tail<<endl;
}
};
int main(){
Dog d;
d.drinkAnimal();
d.eatAnimal();
d.functionDog();
Cat c;
c.drinkAnimal();
c.eatAnimal();
c.functionCat();
c.catInfo();
}

EXAMPLE 3:
Write a program in which three classes containing their own data and function members are
inherited from a single parent class.

#include <iostream>
using namespace std;

class Animal {
public:

string colour;
float averageSpeed;
int numberOfLegs;
int age;

void putInfo () {
cout <<"Enter the colour of Animal: "<<endl;
cin>> colour;
cout <<"Enter the Average Speed of Animal: "<<endl;
cin>>averageSpeed;
cout <<"Enter the Number of Legs of Animal: "<<endl;
cin>>numberOfLegs;
cout <<"Enter the Age of Animal: "<<endl;
cin>>age;
cout <<"********************************"<<endl;
}
void showInfo () {
cout <<"The colour of Animal is: "<<colour<<endl;
cout <<"The Average Speed of Animal is: "<<averageSpeed<<endl;
cout <<"The Number of Legs of Animal is: "<<numberOfLegs<<endl;
cout <<"The Age of Animal is: "<<age<<endl;
cout <<"********************************"<<endl;
}
};
class Cat : public Animal {
public:
string breed;
string voice;
public:
void putCatinfo ()
{
cout <<"Enter the breed of Cat: "<<endl;
cin>> breed;
cout <<"Enter the voice of "<<endl;
cin>>voice;
}

void catInfo () {
cout << "The colour of Cat is: " << colour << endl;
cout << "The Average Speed of Cat is: " << averageSpeed << endl;
cout << "The Number of Legs of cat is: " << numberOfLegs << endl;
cout << "The Age of cat is: " << age << endl;
cout << "The Breed of cat is: " << breed << endl;
cout << "The Voice of cat is: " << voice << endl;
cout <<"********************************"<<endl;
}
};
class Lion : public Animal {
public:
string bravery;
string courage;

void putLioninfo ()
{
cout <<"bravery of Lion is: "<<endl;
cin>> bravery;
cout <<"courage of Lion is "<<endl;
cin>>courage;
}

void lionInfo () {
cout << "The colour of Lion is: " << colour << endl;
cout << "The Average Speed of Lion is: " << averageSpeed << endl;
cout << "The Number of Legs of Lion is: " << numberOfLegs << endl;
cout << "The Age of Lion is: " << age << endl;
cout << "The Bravery of Lion is: " << bravery << endl;
cout << "The Courage of Lion is: " << courage << endl;
cout <<"********************************"<<endl;
}

};

int main () {
Animal Dog ;
Dog.putInfo ();
Dog.showInfo();

Cat c1;
c1.putInfo();
c1.putCatinfo ();
c1.catInfo ();

Lion L1;
L1.putInfo();
L1.putLioninfo ();
L1.lionInfo ();
return 0;
}
—---------------------------------------------------------------------------------------------------

TYPES OF INHERITANCE
There are two types of inheritance:
● Single Inheritance
● Multiple Inheritance
● Multilevel Inheritance.
● Hierarchical Inheritance.
● Hybrid Inheritance

➤Single Inheritance:
When a derived class( child class ) is derived from only one base class/ parent class , then it is called single
inheritance.
➤ Multiple Inheritance:
When a derived class is derived from more than one base class, then it is called multiple inheritance.

➧ Syntax of Multiple Inheritance:


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

➧In Multiple inheritance, a class is derived by using more than one base classes.
➧Derived class receive the members of more than one base classes.
➧ Multiple inheritance is a powerful feature of OOP.
➧ It reduces time and decreases the size of the program.
EXAMPLE:
Write a program and inherit a class from three Parent classes.

#include <iostream>
using namespace std;

class Student {
private:
string name;
string address;
public:
void putInfo () {
cout<<"Enter Name of Student "<<endl;
cin>>name;
cout<<"Enter the address of Student "<<endl;
cin>>address;
}
void showInfo() {
cout<<"The Name of Student is "<<name<<endl;
cout<<"The address of Student is "<<address<<endl;

}
};

class Marks {
private:
int DE,SE, Total;
public:

void putMarks () {
cout<<"Enter the Marks of DE "<<endl;
cin>>DE;
cout<<"Enter the Marks of SE "<<endl;
cin>>SE;
Total = DE+SE;
}
void showMarks () {
cout<<"Your Marks of DE is "<<DE<<endl;
cout<<"Your Marks of SE is "<<SE<<endl;
cout<<"Your Total Marks is "<<Total<<endl;

}
};
class Show : public Student, public Marks {
public:
void showResult () {
cout<<"@@@@@@@@@@@@@@@@@@@@@"<<endl;
cout<<"Record of the Student"<<endl;

putInfo ();
putMarks ();
}
};

int main () {

Show s;
s.showResult ();
s.showInfo();
s.showMarks ();

return 0;
}

CASES IN SINGLE INHERITANCE

CASE 1:
➽ With UN-PARAMETERIZED CONSTRUCTOR

➤If a class has an unparameterized or un-augmented constructor in parent and child class, then
after making an object of the child class , the constructor of parent class will be called out first.

EXAMPLE:
#include<iostream>
using namespace std;
class A{
public:
A( ){
cout<< "I am the constructor of parent class"<<endl;
}
};
class B: public A{
public:
B( ){
cout<<"I am constructor member function of child class"<<endl;
}
};
int main( ){
B obj; //Object created so parent constructor will call out first
}

I am the constructor of parent class


I am constructor member function of child class

--------------------------------
Process exited after 0.2311 seconds with return value 0
Press any key to continue . . .

➽ With destructor
When a destructor is also in the parent or child class, then the calling of the constructor
will be in reverse order i.e. firstly the constructor of child class will call out and then of
parent class.

EXAMPLE:
#include<iostream>
using namespace std;
class A{
public:
A(){
cout<<"constructor of parent class"<<endl;
}
~A(){
cout<<"destructor of parent class"<<endl;
}
};
class B: public A{
public:
B(){
cout<<"constructor of child class"<<endl;
}
~B( ){
cout<< "destructor of child class"<<endl;
}
};
int main(){
B obj;
}

constructor of parent class


constructor of child class
destructor of child class
destructor of parent class

--------------------------------
Process exited after 0.1209 seconds with return value 0
Press any key to continue . . .

Case 2:
WITH PARAMETERIZED CONSTRUCTOR

➮ when the constructor of parent class is with parameters or the constructor is


augmented , we write constructor of the child class with both the parameters of
child class and parent class.
➮ While writing the parameters of child class, the parameters of parent class are written
without datatypes.

Syntax:
class A{
public:
A( int x){ //parameterized constructor of parent class, A
}
};
class B:public A{ //inherited class i.e. class B
public:
B(int x, int y): A(x){ //parameterized constructor of child class ,also inheriting the
} // parameter of parent class but without datatype.
};
int main(){
B obj(a,b);
}

EXAMPLE:
#include<iostream>
using namespace std;
class Parent{
private:
int n1 , n2 ;
public:
Parent(int x , int y){
n1 = x;
n2 = y;
}
void ShowInfoP(){
cout<<"First value of parent constructor="<<n1<<endl;
cout<<"Second value of parent constructor="<<n2<<endl;
}
};
class Child: public Parent{
private:
int p, q ;

public:
Child(int x, int y, int a , int b):Parent(x,y){
p=a;
q=b;
}
void Display(){
cout<<"First value of child constructor="<<p<<endl;
cout<<"Second value of child constructor="<<q<<endl;
}
};
int main(){
Child C(1,2,3,4);
C.ShowInfoP();
C.Display();
}

First value of parent constructor=1


Second value of parent constructor=2
First value of child constructor=3
Second value of child constructor=4

--------------------------------
Process exited after 0.1409 seconds with return value 0
Press any key to continue . . .
CASES IN MULTIPLE INHERITANCE

CASE 1:
WITH UNPARAMETERIZED CONSTRUCTOR

➤When a class is derived from more than one base classes , the constructors of derived
class as well as of base classes are executed as an object of derived class is created.

➤ If the constructor function have no parameters , then in that case , firstly the constructor
function of base class is executed and then of the derived class is executed.

➤ The constructors of base class are not inherited in child class.

EXAMPLE:
#include<iostream>
using namespace std;
class ParentA{
public:
ParentA(){
cout<<"Constructor of parentA class"<<endl;
}
};
class ParentB{
public:
ParentB(){
cout<<"Constructor of parentB class"<<endl;
}
};
class ChildC: public ParentA, public ParentB{
public:
ChildC(){
cout<<"Constructor of childC class"<<endl;
}
};
int main(){
ChildC obj;
}

Constructor of parentA class


Constructor of parentB class
Constructor of childC class

--------------------------------
Process exited after 0.1239 seconds with return value 0
Press any key to continue . . .

CASE 2:
WITH PARAMETERIZED CONSTRUCTOR

➤ When the constructor is parameterized , the syntax of writing the child class will be as
follow:
class Child: public ParentA, public ParentB{
//constructor Child(int x, int y, int p, int q, int f, int g): ParentA(x,y) , ParentB(
p,q){

};

Example:
#include <iostream>
using namespace std;

class Parent1 {
private:
int x;

public:
Parent1(int a) {
x=a;
cout << "Parent1 constructor called with x = " << x << endl;
}

void displayParent1() {
cout << "Data from Parent1: " << x << endl;
}
};

class Parent2 {
private:
int y;

public:
Parent2(int b) {
y=b;
cout << "Parent2 constructor called with y = " << y << endl;
}

void displayParent2() {
cout << "Data from Parent2: " << y << endl;
}
};

class Child : public Parent1, public Parent2 {


private:
int z;

public:
Child(int a, int b, int c) : Parent1(a), Parent2(b) {
z=c;
cout << "Child constructor called with z = " << z << endl;
}

void displayChild() {
displayParent1();
displayParent2();
cout << "Data from Child: " << z << endl;
}
};

int main() {
Child obj(10, 20, 30);
obj.displayChild();

return 0;
}

Parent1 constructor called with x = 10


Parent2 constructor called with y = 20
Child constructor called with z = 30
Data from Parent1: 10
Data from Parent2: 20
Data from Child: 30

--------------------------------
Process exited after 0.1814 seconds with return value 0
Press any key to continue . . .
Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.

Example:

#include <iostream>
using namespace std;

class Device {
public:
void powerOn() {
cout << "Device is powered on" << endl;
}
};

class Smartphone : public Device {


public:
void makeCall() {
cout << "Making a call from smartphone" << endl;
}
};

class AndroidPhone : public Device {


public:
void installApp() {
cout << "Installing app on Android phone" << endl;
}
};

class IPhone : public AndroidPhone, public Smartphone {


public:
void king() {
cout << "Iphone is King :) " << endl;
}
};

int main() {
IPhone myPhone;
myPhone.makeCall();
myPhone.installApp();
myPhone.king();

Smartphone obj;
obj.powerOn ();

return 0;
}
Multi-Level Inheritance

→ Multilevel Inheritance is the type of inheritance in which the super class is derived by the child class,
The child class is derived to another child class.
→ Multilevel Inheritance in which the drive class is derived by another drive class.

Example 1
—------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

class Grandfather {
public:
void wisdom() {
cout << "Grandfather shares wisdom" << endl;
}
};

class Father : public Grandfather {


public:
void work() {
cout << "Father goes to work" << endl;
}
};
class Child : public Father {
public:
void play() {
cout << "Child plays in the park" << endl;
}
};

int main() {
Child myChild;

myChild.wisdom();
myChild.work();
myChild.play();

return 0;
}

Hierarchical Inheritance

→ The inheritance in which a single base class inherits multiple derived classes is known as the
Hierarchical Inheritance.
→ This inheritance has a tree-like structure since every class acts as a base class for one or more child
classes.

Example 1
—------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

class Data {
protected:
int a,b;
public:
void getInfo () {
cout<<"Enter Any Number "<<endl;
cin>> a;
cout<<"Enter Second Number "<<endl;
cin>>b;
}
};

class Sum : public Data {


public :
void showSum () {
cout<<"The Sum of Two Numbers is: "<<a+b<<endl;
}
};

class Subtraction : public Data {


public :
void showSubtraction () {
cout<<"The Subtraction of Two Numbers is: "<<a-b<<endl;
}
};

class Multiplication : public Data {


public :
void showMultiplication () {
cout<<"The Multiplication of Two Numbers is: "<<a*b<<endl;
}
};

class Division : public Data {


public :
void showDivision () {
cout<<"The Division of Two Numbers is: "<<a/b<<endl;
}
};

int main () {
Sum s1;
s1.getInfo ();
s1.showSum ();
system("pause");
system("CLS");

Subtraction s2;
s2.getInfo();
s2.showSubtraction();
system("pause");
system("CLS");

Multiplication m;
m.getInfo();
m.showMultiplication();
system("pause");
system("CLS");

Division d;
d.getInfo();
d.showDivision();

return 0;
}

—------------------------------------------------------------------------------------------------------

Example 2:
—------------------------------------------------------------------------------------------------------
#include <iostream>
using namespace std;

class Student {
private:
int roll_Number;
string name;

public:
void getInfo (){
cout<<"Enter Name "<<endl;
cin>>name;
cout<<"Enter Roll Number "<<endl;
cin>>roll_Number;
}

void showInfo (){


cout<<"Your Name is: "<<name<<endl;
cout<<"Your Roll Number is: "<<roll_Number<<endl;
}
};

class Freelancer : public Student {


private:
int earning, id;
public:
void getFreelancer (){
cout<<"Enter ID "<<endl;
cin>>id;
cout<<"Enter Earning "<<endl;
cin>>earning;
}
void showFreelancer () {
cout<<"Your Id is: "<<id<<endl;
cout<<"Your Earning is: "<<earning<<endl;
}
};
class Developer: public Student {
private:
string app;

public:
void getDeveloper (){
cout<<"Enter the CMS on which you work "<<endl;
cin>>app;
}
void showDeveloper (){
cout<<"The CMS you use is: "<<app<<endl;

}
};

int main (){


Freelancer f;
f.getInfo();
f.getFreelancer();
f.showInfo();
f.showFreelancer ();
system ("pause");
system ("CLS");

Developer d;
d.getInfo();
d.getDeveloper();
d.showInfo();
d.showDeveloper();
}

—------------------------------------------------------------------------------------------------------

More Relationships between classes


1. Association
2. Aggregation
3. Composition

What is a Relationship?
It is a connection between two things like a relationship between parents, relatives, students & teachers,
department & employees, car & engine, car & driver.
Association
It represents the simple relationship between two objects, where one object uses the other object.
1. it is an open relationship.
2. If one object is destroyed there is no effect on the other object
3. Each object is independent, i.e, teacher & student, Patient & doctor,
● If object of teacher is destroyed, no effect on student
● If object of student is destroyed no effect on teacher
4. Association can be of three types i.e :One to one
5. One to many
6. Many to Many

Aggregation
It represents simple relationship between two objects where one object contains the other objects, and
the child object cannot belong to the other parent object at same time

1. has - a- relationship
2. For Example, between department & Employes
3. If parent is destroyed, still the child will do exit
4. If we delete parent object, in has-a-relationship between the department and employees, the child
object exists.

Composition
Represents a strong relationship between two objects where one object own the other object. Child
object doesn't have their own life cycle.
For Example: Between car and engine, b/w person and happy birthday
→ if the parent object is deleted, then child object will be deleted automatically

—-------------------------------------------------------------------------------------------------------
Polymorphism
The term "Polymorphism" is the combination of "poly" and "morphs" which means many forms.
Polymorphism is defined as the process of using a function or an operator for more than one purpose.

Example: A girl behaves like a teacher in a classroom, mother or daughter in a home and customer in a
market.

There are two types of polymorphism in C++:


1. Compile time polymorphism
● Function Overloading
● Operator Overloading
2. Virtual Function

—--------------------------------------------------------------------------------------------------------------------------------
Function OverLoading Example
—-----------------------------
#include <iostream>
using namespace std;

class FunctionOverLoading {
public:
void function(){
cout<<"This is a function without parameters"<<endl;
}
void function(int x){
cout<<"This is a function with one parameters and integer data type"<<endl;
}
void function (double x){
cout<<"Function with one parameter and double data type"<<endl;
}
};

int main (){


FunctionOverLoading f1;
f1.function();
f1.function(2.6);
f1.function(8);

—--------------------------------------------------------------------------------------------------------------------------------

Virtual Function
If there are member functions with the same name in base class and derive class virtual function gives
programmer capability to call member functions of different classes by the same function. Calling
depends upon different context. It supports run time polymorphism.
→ virtual function must be member of some classes
→ virtual function enable drive/subclass to provide its own implementation for the function already
defined in the base class
→ virtual function cannot be a static member (i.e. data/function member).
→ only the functions that are members of some classes can be declared as virtual. This mean we cannot
declare regular function or friend function as a virtual

Example

#include <iostream>
using namespace std;

class Parent {
public:
virtual void show() {
cout << "Member function of parent class " << endl;
}
};

class Child : public Parent {


public:
void show() {
cout << "Member function of Child class" << endl;
}
};
class Baby : public Parent {
public:
void show() {
cout << "Member function of Baby class" << endl;
}
};

int main() {
Parent* P;
Child c;
Baby b;

P = &c;
P->show();

P = &b;
P->show();

return 0;
}
—--------------------------------------------------------------------------------------------------------------------------------

Abstract Class
1. A class that contains pure virtual function is called an abstract class.
2. An abstract class cannot be instantiated (means we can’t create object of abstract class )
3. Pointor (P*) and reference variable(&) of abstract class can be created
4. An abstract class can have normal function variable with pure virtual function.
5. A pure virtual function has no definition (mean no body & no starting and ending brackets)
6. They start with a virtual keyword and end with zero.

Notes: Virtual Function () = 0;

Static Property
1. Static property is property of class i.e. common for all objects.
2. Static means that a fix value is assigned to all
3. Keyword of static is used before the names of data & function members
4. To access a static property, we use the name of class with the property.
i.e. class name.property name

Example:
Datamember:
static int BSCS-GCUF2022;
Function:
static void getInfo( ){
}

You might also like