Docsity

Understanding Access Specifiers, Inheritance, and Member Access in C++, Slides of Object Oriented Programming

Partial preview of the text

Download Understanding Access Specifiers, Inheritance, and Member Access in C++ and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 23

Date Class

class Date{ int day, month, year; static Date defaultDate; public: void SetDay(int aDay); int GetDay() const; void AddDay(int x); … static void SetDefaultDate( int aDay,int aMonth, int aYear); Docsity.com

Creating SpecialDate Class

Special Date

Date (^) Special Date

AddSpecialYear ...

Creating SpecialDate Class

class SpecialDate: public Date{ … public: void AddSpecialYear(int i){ ... if(day == 29 && month == 2 && !IsLeapyear(year+i)){ //ERROR! ... } } };

Modified Date Class

class Date{

public:

bool IsLeapYear();

Modified AddSpecialYear

void SpecialDate :: AddSpecialYear

(int i){ ... if(day == 29 && month == 2 && !IsLeapyear(year+i)){ ... }

}

Modified Date Class

class Date{ … protected: bool IsLeapYear(); };

int main(){ Date aDate; aDate.IsLeapYear(); //Error return 0; }

Modified AddSpecialYear

void SpecialDate :: AddSpecialYear

(int i){ ... if(day == 29 && month == 2 && !IsLeapyear(year+i)){ ... }

}

“IS A” Relationship

• Public inheritance models the “IS

A” relationship

• Derived object IS A kind of base

object

Example

class Person { char * name; public: ... const char * GetName(); }; class Student: public Person{ int rollNo; public: ... int GetRollNo(); };

“IS A” Relationship

  • The base class pointer can point

towards an object of derived class

int main(){

Person * pPtr = 0; Student s; pPtr = &s; cout << pPtr->GetName();

return 0;

}

Example

int main(){

Person * pPtr = 0; Student s; pPtr = &s; //Error cout << pPtr->GetRollNo(); return 0;

}

Example

Static Type

• The type that is used to declare a

reference or pointer is called its

static type

  • The static type of pPtr is Person
  • The static type of s is Student