OOP With C - (Module 3) (1) ..
OOP With C - (Module 3) (1) ..
Inheritance
• In C++, inheritance is a process in which one object acquires all the
properties and behaviors of its parent object automatically.
• In such way, you can reuse, extend or modify the attributes and behaviors
which are defined in other class.
• In C++, the class which inherits the members of another classis called
derived class and the class whose members are inherited is called base
class.
• The derived class is the specialized class for the base class.
• Code reusability: Now you can reuse the members of your parent class. So,
there is no need to define the member again. So less code is required in
the class.
Derived Classes
• A Derived class is defined as the class derived from the base class.
• derived_class_name: It is the name of the derived class.
• visibility mode: The visibility mode specifies whether the features of
the base class are publicly inherited or privately inherited. It can be
public or private.
• base_class_name: It is the name of the base class.
• When the base class is privately inherited by the derived class, public
members of the base class becomes the private members of the
derived class. Therefore, the public members of the base class are not
accessible by the objects of the derived class only by the member
functions of the derived class.
• When the base class is publicly inherited by the derived class, public
members of the base class also become the
public members of the derived class. Therefore, the public
members of the base class are accessible by the objects of the
derived class as well as by the member functions of the base class.
Types Of Inheritance
#include <iostream> using
namespace std; class
Account {
public:
float salary = 60000;
• Single inheritance is };
defined as the inheritance class Programmer: public Account {
in which a derived class is public:
inherited from the only float bonus = 5000;
one base class. };
• Where 'A' is the base int main(void) {
Programmer p1;
class, and 'B' is the cout<<"Salary: "<<[Link]<<endl;
derived class. cout<<"Bonus: "<<[Link]<<endl;
return 0;
}
#include <iostream> using
namespace std; class A
{
int a = 4;
int b = 5;
public:
int mul()
{ int c = a*b;
return c;
}
};
class B : private A
{
public:
void display()
{
int result = mul();
std::cout <<"Multiplication of a and b is : "<<result<< std::endl;
}
};
int main()
{
B b;
[Link]();
return 0;
}
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
• Multilevel Inheritance is a };
process of deriving a class class BabyDog: public Dog
from another derived class. {
public:
void weep() {
cout<<"Weeping...";
}
#include <iostream> };
using namespace std; int main(void) {
class Animal { BabyDog d1;
public: [Link]();
void eat() [Link]();
{ [Link]();
cout<<"Eating..."<<endl; return 0;
} }
};
• Multiple inheritance is the process of deriving a new class that
inherits the attributes from two or more classes.
#include <iostream>
using namespace std; class C : public A,public B
class A {
{ public:
protected: void display()
int a; {
public: std::cout << "The value of a is : " <<a<< std::endl;
void get_a(int n) std::cout << "The value of b is : " <<b<< std::endl;
{ cout<<"Addition of a and b is : "<<a+b;
a = n; }
} };
}; int main()
class B {
{ C c;
protected: c.get_a(10);
int b; c.get_b(20);
public: [Link]();
void get_b(int n)
{ return 0;
b = n; }
}
};
• Hybrid inheritance is a combination of more than one type of
inheritance.
#include <iostream> class D : public B, public C
using namespace std; {
class A { protected:
protected: int d;
int a; public:
public: void mul()
void get_a() {
{ cout << "Enter the value of 'a' : " << endl; get_a();
cin>>a; get_b();
} }; get_c();
class B : public A { cout << "Multiplication of a,b,c is : " <<a*b*c;
protected: }
int b; };
public: int main()
void get_b() {
{ cout << "Enter the value of 'b' : " << endl; D d;
cin>>b; [Link]();
} }; return 0;
class C }
{ protected: int c; public:
void get_c()
{ cout << "Enter the value of c is : " << endl;
cin>>c;
} };
• Hierarchical inheritance is defined as class A
{
the process of deriving more than // body of the class
one class from a base 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.
}
#include <iostream>
using namespace std;
class Shape
{public:
int main()
int a;
{ Rectangle r;
int b;
Triangle t;
void get_data(int n,int m)
int length,breadth,base,height;
{ a= n;
cout << "Enter the length and breadth of a rectangle: " << endl;
b=m;
cin>>length>>breadth;
} };
r.get_data(length,breadth);
class Rectangle : public Shape
int m = r.rect_area();
{ public:
cout << "Area of the rectangle is : " <<m<< endl;
int rect_area()
cout << "Enter the base and height of the triangle: " << endl;
{ int result = a*b;
cin>>base>>height;
return result;
t.get_data(base,height);
} };
float n = t.triangle_area();
class Triangle : public Shape
cout <<"Area of the triangle is : " << n<<endl;
{ public:
return 0;
int triangle_area()
}
{ float result = 0.5*a*b;
return result;
} };
Constructor/ destructor in Inheritance
#include <iostream> class child: public parent
using namespace std; {
class parent public:
child()
{
{
public: cout<<"child class constructor"<<endl;
parent() }
~child()
{ {
cout<<"parent class constructor"<<endl; cout<<"child class destructor"<<endl;
}
} };
~parent() int main() {
{ child c1;
return 0;
cout<<"parent class destructor"<<endl; }
}
};
#include <iostream>
using namespace std;
int main() {
// Base class Student s;
class Person { [Link]("Suraj"); // setName is public
protected: [Link]();
string name; // Protected member return 0;
}
public:
void setName(string n) {
name = n;
}
};
// Derived class
class Student : public Person {
public:
void display() {
cout << "Student Name: " << name << endl;
}
};
The way those members are inherited depends on the type of inheritance:
•public
•protected
•private
Base Class Member Type Public Inheritance Protected Inheritance Private Inheritance
public public protected private
protected protected protected private
private Not inherited Not inherited Not inherited
Accessible from outside
#include <iostream>
using namespace std;
class Base {
public:
int pub = 1;
protected:
int prot = 2;
private:
int priv = 3;
};
class PublicDerived : public Base {
public:
void display() {
cout << "Public: " << pub << endl; // OK
cout << "Protected: " << prot << endl; // OK
// cout << "Private: " << priv << endl; // Error
}
};
class ProtectedDerived : protected Base {
public:
void display() {
cout << "Public becomes Protected: " << pub << endl; // OK
cout << "Protected: " << prot << endl; // OK
}
};
class PrivateDerived : private Base {
public:
void display() {
cout << "Public becomes Private: " << pub << endl; // OK
cout << "Protected becomes Private: " << prot << endl; // OK
}
};
int main() {
PublicDerived obj1;
[Link]();
cout << [Link] << endl; // OK: remains public Public: 1
Protected: 2
ProtectedDerived obj2; Public becomes Protected: 1
[Link](); Protected: 2
// cout << [Link] << endl; // Error: now protected Public becomes Private: 1
Protected becomes Private: 2
PrivateDerived obj3; 1
[Link]();
// cout << [Link] << endl; // Error: now private
return 0;
}
Function overriding
• Function overriding occurs when a derived class has a member
function with the same name, return type, and parameters as a
virtual function in the base class
#include <iostream>
using namespace std; int main() {
Animal* a; // Base class pointer
// Base class Dog d; // Derived class object
class Animal { a = &d;
public:
virtual void makeSound() { a->makeSound(); // Calls Dog::makeSound because
cout << "Animal makes a sound" << endl; of virtual function
} return 0;
}; }
// Derived class
class Dog : public Animal {
public:
void makeSound() override { // overrides
Animal::makeSound
cout << "Dog barks" << endl;
}
};
• An abstract class in C++ is a class that cannot be instantiated and is
typically used as a base class. It contains at least one pure virtual
function.
• A pure virtual function is a function that has no definition in the base
class and must be overridden in derived classes.
#include <iostream> // Another Derived Class
using namespace std; class Cat : public Animal {
public:
// Abstract Base Class void makeSound() override {
class Animal { cout << "Cat meows" << endl;
public: }
virtual void makeSound() = 0; // Pure };
virtual function
int main() {
void breathe() { // Animal a; // Error: Cannot instantiate
cout << "Animal breathes" << endl; abstract class
}
}; Animal* d = new Dog();
Animal* c = new Cat();
// Derived Class
class Dog : public Animal { d->makeSound(); // Output: Dog barks
public: c->makeSound(); // Output: Cat meows
void makeSound() override {
cout << "Dog barks" << endl; delete d;
} delete c;
};
return 0;
}
#include <iostream>
int main() {
int var = 10;
• A pointer is a special variable that // declare pointer and store address of x
holds the memory address of int* ptr = &var;
another variable, rather than storing
a direct value itself. // print value and address
• Pointers allow programs to access cout << "Value of x: " << var << endl;
and manipulate data in memory cout << "Address of x: " << &var << endl;
efficiently, making them a key cout << "Value stored in pointer ptr: " << ptr << endl;
feature for system-level cout << "Value pointed to by ptr: " << *ptr << endl;
programming and dynamic memory
management. return 0;
}
• When we access a pointer directly, Value of x: 10
int main() {
● The new operator in C++ allocates
// Declared a pointer to store
memory from the Free Store (a // the address of the allocated
memory
portion of the heap). If enough int *nptr;
memory is available, it initializes
// Allocate and initialize memory
the memory with a default value nptr = new int(6);
based on its type and returns the
// Print the value
address of the allocated memory cout << *nptr << endl;
int main() {
// Print array
for (int i = 0; i < 5; i++)
cout << nptr[i] << " ";
return 0;
}
delete Operator
In C++, delete operator is used to release dynamically allocated memory. It
deallocates memory that was previously allocated with new.
Syntax
delete ptr;
base_class_pointer = &obj_derived;
base_class_pointer->var_base = 34;
// If you uncomment this line of code this will cause the following error As base-class pointer cannot
// access the derived class variable. base_class_pointer->var_derived = 98;
// output: error: ‘class BaseClass’ has no member named ‘var_derived’
● Virtual functions ensure that the correct function is called for an object, regardless of
the type of reference (or pointer) used for the function call.
● They are mainly used to achieve Runtime polymorphism.
int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display();
return 0;
}
#include <iostream>
using namespace std;
class base {
public:
virtual void print() { int main() {
cout << "print base " base* bptr;
"class\n"; derived d;
} bptr = &d;
// Virtual function,
void show() { // binded at runtime
cout << "show base class\n"; bptr->print();
} // Non-virtual function,
}; // binded at compile time
class derived : public base { bptr->show();
public: return 0;
void print() { }
cout << "print derived class\n";
}
void show() {
cout << "show derived class\n";
}
};
int main() {
base* p;
derived obj1;
#include <iostream>
p = &obj1;
using namespace std;
// Early binding because fun1() is non-virtual
class base {
// in base
public:
p->fun_1();
void fun_1() { cout << "base-1\n"; }
virtual void fun_2() { cout << "base-2\n"; }
// Late binding (RTP)
virtual void fun_3() { cout << "base-3\n"; }
p->fun_2();
virtual void fun_4() { cout << "base-4\n"; }
};
// Late binding (RTP)
p->fun_3();
class derived : public base {
public:
// Late binding (RTP)
void fun_1() { cout << "derived-1\n"; }
p->fun_4();
void fun_2() { cout << "derived-2\n"; }
void fun_4(int x) { cout << "derived-4\n"; }
// Early binding but this function call is
};
// illegal (produces error) because pointer
// is of base type and function is of
// derived class
// p->fun_4(5);
return 0;
}
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
3. Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime
polymorphism.
4. The prototype of virtual functions should be the same in the base as well as the derived class.
5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the
derived class to override (or re-define the virtual function), in that case, the base class version of the
function is used.
6. A class may have a virtual destructor, but it cannot have a virtual constructor.
Virtual Destructor
• Deleting a derived class object using a pointer of base class type that
has a non-virtual destructor results in undefined behavior. To correct
this situation, the base class should be defined with a virtual destructor.
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
virtual ~base()
{ cout << "Destructing base\n"; }
};
class derived : public base {
public:
derived()
{ cout << "Constructing derived\n"; }
~derived()
{ cout << "Destructing derived\n"; }
};
int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
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. Remember one thing, Friendship is
not mutual. If class A is a friend of B, then B doesn't become a friend of A
automatically.
• We can declare a friend class in C++ by using the friend keyword.
#include <iostream> // class GFG is declared as a friend
using namespace std; // inside class Geeks, therefore
// Class GFG can access private members of class Geeks.
class Geeks { class GFG {
private: public:
int private_variable; void display(Geeks& t) {
cout << "The value of Private Variable = "
protected: << t.private_variable << endl;
int protected_variable; cout << "The value of Protected Variable = "
<< t.protected_variable;
public: }
Geeks() { };
private_variable = 10;
protected_variable = 99; int main() {
} Geeks g;
GFG fri;
// friend class declaration [Link](g);
friend class GFG; return 0;
}; }
Output
The value of Private Variable = 10
The value of Protected Variable = 99
Friend Function
Like friend classes, 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.
We can also declare a member function of another class as a friend function in C++.
Forward declaration of the class is needed if we want to make a member function of
another class a friend inside that class.
#include <iostream>
using namespace std;