Docsity

Inheritance and Memory Allocation in Object-Oriented Programming (OOP) using C++, Slides of Object Oriented Programming

Partial preview of the text

Download Inheritance and Memory Allocation in Object-Oriented Programming (OOP) using C++ and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 22

Inheritance in Classes

  • If a class B inherits from class A, then B contains all the characteristics (information structure and behavior) of class A
  • The parent class is called base class and the child class is called derived class
  • Besides inherited characteristics, derived class may have its own unique characteristics

Inheritance in C++

• There are three types of

inheritance in C++

  • Public
  • Private
  • Protected

“IS A” Relationship

  • IS A relationship is modeled with the help of public inheritance
  • Syntax

class ChildClass : public BaseClass{ ... };

Accessing Members

• Public members of base class

become public member of derived

class

• Private members of base class

are not accessible from outside of

base class, even in the derived

class (Information Hiding)

Example

class Person{

char *name; int age; ...

public:

const char *GetName() const; int GetAge() const; ...

};

Example

void Student::Print()

{

cout << name << “ is in” << “ semester ” << semester;

}

ERROR

Example

void Student::Print()

{

cout << GetName() << “ is in semester ” << semester;

}

Allocation in Memory

• The object of derived class is

represented in memory as follows

Data members of base class

Data members of derived class

base member base member ...

derived member derived member ...

Allocation in Memory

• Every object of derived class has

an anonymous object of base

class

Constructors

Base class constructor initializes the anonymous object

Derived class constructor initializes the derived class object

base member base member ...

derived member derived member ...

class Parent{

public:

Parent(){ cout << “Parent Constructor...”;}

};

class Child : public Parent{

public:

Child(){ cout << “Child Constructor...”;}

};

Example

Constructor

• If default constructor of base

class does not exist then the

compiler will try to generate a

default constructor for base class

and execute it before executing

constructor of derived class

Constructor

• If the user has given only an

overloaded constructor for base

class, the compiler will not

generate default constructor for

base class