Docsity

Overriding Member Functions - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Overriding Member Functions - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 25

Overriding Member Functions of

Base Class

  • Derived class can override the member functions of its base class
  • To override a function the derived class simply provides a function with the same signature as that of its base class

Overriding

class Parent { public: void Func1(); void Func1(int); };

class Child: public Parent { public: void Func1(); };

Overloading vs. Overriding

  • Overloading is done within the scope of one class
  • Overriding is done in scope of parent and child
  • Overriding within the scope of single class is error due to duplicate declaration

Overriding Member Functions of

Base Class

  • Derive class can override member function of base class such that the working of function is totally changed

Example

class Person{

public:

void Walk();

};

class ParalyzedPerson: public Person{

public:

void Walk();

};

Example

**class Person{ char *name; public: Person(char =NULL); const char GetName() const; void Print(){ cout << “Name: ” << name << endl; } }; Docsity.com

Example

class Student : public Person{ char * major; public: Student(char * aName, char aMajor);*

void Print(){ cout <<“Name: ”<< GetName()<<endl << “Major:” << major<< endl; } ... };

Output

Output:

Name: Ahmed

Major: Computer Science

Overriding Member Functions of

Base Class

  • Derive class can override member function of base class such that the working of function is based on former implementation

Example

int main(){

Student a(“Ahmad”, “Computer Science”); a.Print(); return 0;

}

Output

  • There will be no output as the compiler will call the print of the child class from print of child class recursively
  • There is no ending condition

Example

int main(){

Student a(“Ahmad”, “Computer Science”); a.Print(); return 0;

}

Output

Output:

Name: Ahmed

Major: Computer Science