In: Computer Science
IN C++, IN C++, IN C++, IN C++, IN C++
Write the A and B classes, the properties of which will produce
the expected output with the test code provided, and the
characteristics of which are specified below. Note the types of
pointers used in the test code.
Methods of class A:
- void hi () - Prints “Hi A” on the screen.
- void selam() - Prints "Selam A" on the screen.
Class B must inherit class A. Class methods should be written so
that access levels can produce the desired output in the test code
provided.
Test code:
int main() {
A* ptrA1 = new A{};
A* ptrB1 = new B{};
B* ptrB2 = new B{};
ptrA1->selam();
ptrA1->hi();
ptrB1->selam();
ptrB1->hi();
ptrB2->selam();
ptrB2->hi();
return 0;
}
Expected output:
Selam A
Hi A
Selam A
Hi B
Selam B
Hi B
Solution:
#include<iostream>
using namespace std;
class A
{
public:
virtual void hi()
{
cout<<"Hi A"<<endl;
}
void selam()
{
cout<<"Selam A"<<endl;
}
};
class B : public A
{
public:
void hi()
{
cout<<"Hi B"<<endl;
}
void selam()
{
cout<<"Selam B"<<endl;
}
};
int main()
{
A* ptrA1 = new A();
A* ptrB1 = new B();
B* ptrB2 = new B();
ptrA1->selam();
ptrA1->hi();
ptrB1->selam();
ptrB1->hi();
ptrB2->selam();
ptrB2->hi();
return 0;
}
Output:
Please give thumbsup, or do comment in case of any query. Thanks.