This section contains the C++ find output programs with their explanations on C++ Inheritance (set 2).
Program 1:
#include <iostream>
#include <string.h>
using namespace std;
class Person {
char name[15];
int age;
protected:
void SetPerson(int age, char* name)
{
this->age = age;
strcpy(this->name, name);
}
void PrintPerson()
{
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
class Student {
int student_id;
int fees;
public:
Student(int id, int fee, int age, char* name)
{
student_id = id;
fees = fee;
SetPerson(age, name);
}
void Print()
{
cout << "Student id: " << student_id << endl;
cout << "Fees: " << fees << endl;
PrintPerson();
}
};
int main()
{
Student S(101, 5000, 5, "Shaurya");
S.Print();
return 0;
}
Program 2:
#include <iostream>
#include <string.h>
using namespace std;
class Class1 {
public:
Class1()
{
cout << "Class1 ctor called " << endl;
}
};
class Class2 : public Class1 {
public:
Class2()
{
cout << "Class2 ctor called " << endl;
}
};
int main()
{
Class2 OB;
return 0;
}
Program 3:
#include <iostream>
#include <string.h>
using namespace std;
class Class1 {
public:
Class1()
{
cout << "Class1 ctor called " << endl;
}
};
class Class2 : public Class1 {
public:
Class2()
{
cout << "Class2 ctor called " << endl;
}
};
typedef class Class3 : public Class2 {
public:
Class3()
{
cout << "Class3 ctor called " << endl;
}
} DerivedClass;
int main()
{
DerivedClass* PTR;
PTR = new DerivedClass();
return 0;
}
Answer Program 1:
Output:
Explanation:
It will generate errors because, we did not inherit Person class in Student class and accessing the protected members of Person class in the Student class.
Answer Program 2:
Output:
Explanation:
Here, we created two classes Class1 and Class2. Both classes contain constructors.
Class2 inherits Class1, in the main() function, we created the object OB of Class2. Then it called the constructor of Class1 and then it called the constructor of Class2.
In C++, the base class constructor always called before the derived class constructor.
Answer Program 3:
Output:
Explanation:
Here, in the above program, we created three classes Class1, Class2, and Class3, each of them are containing a default constructor.
Here, Class1 is inherited by Class2 and Class2 inherited by Class2. We also created alias using the typedef of Class3 that is Derived class. This type of inheritance is known as multi-level inheritance.
In the main() function, we created the pointer of DerivedClass and pointer of the DerivedClass initialized using the new operator.
Then, Class1 constructor called before Class2 and Class2 constructor called before Class3.
need an explanation for this answer? contact us directly to get an explanation for this answer