Data Members and Member Functions
In this, we are going to see how Data Members and Member Functions works in Hierarchical Inheritance  in C++ Programming Language.
 


The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include<conio.h>

// base class
class university
{
    private:
    char *university_name;

    public:
    char *getUniversityName()
    {
	university_name = "XYZ University";
	return university_name;
    }
};


// derived class 1 inheriting the base class
class student : public university
{
    public:
    void display_student()
    {
	cout << "I am a student of the " << getUniversityName() << ".\n\n";
    }
};

// derived class 2 inheriting the base class
class faculty : public university
{
    public:
    void display_faculty()
    {
	cout << "I am a professor in the " << getUniversityName() << ".\n\n";
    }
};

void main()
{
    clrscr();
    // object of the derived class 1
    student obj1;
    // call the display_student() function of the derived class 1
    obj1.display_student();

    // object of the derived class 2
    faculty obj2;
    // call the display_student() function of the derived class 2
    obj2.display_faculty();
    
    getch();
}

//.......Coded by RISHAB NAIR

The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
using namespace std;

// base class
class university
{
    private:
    string university_name;

    public:
    string getUniversityName()
    {
        university_name = "XYZ University";
        return university_name;
    }
};

// derived class 1 inheriting the base class
class student : public university
{
    public:
    void display_student()
    {
        cout << "I am a student of the " << getUniversityName() << ".\n\n";
    }
};

// derived class 2 inheriting the base class
class faculty : public university
{
    public:
    void display_faculty()
    {
        cout << "I am a professor in the " << getUniversityName() << ".\n\n";
    }
};

int main()
{
    // object of the derived class 1
    student obj1;
    // call the display_student() function of the derived class 1
    obj1.display_student();

    // object of the derived class 2
    faculty obj2;
    // call the display_student() function of the derived class 2
    obj2.display_faculty();
    
    return 0;
}

//.............Coded by RISHAB NAIR

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post