1. Introduction

As promised in my previous blog on inheritance , we’ll take up an interesting example to get a better grip on inheritance concept ☺️ .

2. Base class, Social Media

In order to design the base class, we’ll need to figure out the common features of all the social media that we use. I can think of: Name of social media, number of letters per post (twitter allows 140), good for sharing pics/text/both, popularity, owned by (company name), advertising level and so on..

3. Social Media class definition

As per the various features identified for the base class in above section, the definition of the class will be as follows:

class socialMediaBase

{

protected:

char mediaName[NAMESIZE];

int noOfLettersAllowed;

int sharePicsTextBoth;

int popularityLevel;

Char *ownedByCompany;

Int isGoodForAdvert;

public:

void setMediaName(char *mediaName);

}; //Social Media Class Definition over

4. Derived class, Facebook

Class facebookDer:public socialMediaBase

{

char albumName[NAMESIZE];

public:

SetPhotoAlbumName(char *albumName);

};

Since facebookDer class is derived from socialMediaBase class, all the parameters of base class are available in facebook class also.

In facebook, we have options to create photo albums. We have added a class function to facebookDer class for the same.

5. Derived class, Twitter

class twitterDer:public socialMediaBase

{

int allowRetweet;

public:

void isRetweetAllowed(int isAllowed);

}; // twitter class definition over

All of socialMediaBase class parameters are available to twitterDer class due to inheritance. Retweet is specific to twitter, so its function is added in twitterDer class.

6. Implemetation

Lets define the main function now. We create 2 objects, one each of twitter and facebook class. We set the media name using the base class function setMediaName . Then, functions specific to derived classes are called.

#include <iostream>

Using namespace std;

int main (void)

{

facebookDer objFacebook;

twitterDer objTwitter;

//Base class function setMediaName is //accessible by derived class object;

objFacebook.setMediaName(“Facebook”);

//Facebook class function

objFacebook.setPhotoAlbumName(“friends”);

objTwitter.setMediaName(“Twitter”);

objTwitter.isRetweetAllowed(NO);

} //End Main function

Summary

Friends, I hope you enjoyed this example as much as I did creating it ☺️ . Please feel free to write to me for any clarifications.

Happy learning ☺️ .