Answer to Question #319507 in C++ for thaphy

Question #319507

write a c++ program to demonstrate hierachical inheritance to get square and cube of a number. Base class must calculate square of a number whilst Base class2 caculates cube of a numberr


1
Expert's answer
2022-03-28T11:00:49-0400
#include <iostream>
using namespace std;

class Base {
public:
    Base(int n) : number(n) {}
    virtual int Calculate() { return number*number; }

protected:
    int number;
};


class Base2 : public Base {
public:
    Base2(int n) : Base(n) {}
    int Calculate() { return Base::Calculate() * number; }
};


int main() {
    Base *b = new Base(3);
    cout << "Base: " << b->Calculate() << endl;
    delete b;

    b = new Base2(3);
    cout << "Base2: " << b->Calculate() << endl;
    delete b;

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog