Using polymorphic assignment
I very new to C++ programming and trying to understand this polymorphic assignment thing. I have researched online and have seen multiple examples but the only one that makes sense is tracking non-polymorphic memory footprint where you have parent classes and derived classes. What if you have a parent class then multiple deriv开发者_如何转开发ed classes. How do you call a method in the parent class using polymorphic assignments of variable of pointer type of a base class. Thus, producing the output of the parent class and the derived classes using that method. All I'm asking is for clarity as you should find in a book so I can understand this concept. Then I will create my own test cases. I appreciate any help!
#include<iostream>
using namespace std;
class base
{
public:
int baseVariable;
base(int arg=0):baseVariable(arg) {}
virtual void print()=0;
};
class derivedOne:public base
{
public:
derivedOne(int arg=0):base(arg){}
void print()
{
cout<<"Printing with derivedOne's print function.baseVarible = "<< base::baseVariable<<endl;
}
};
class derivedTwo:public base
{
public:
derivedTwo(int arg=0):base(arg){};
void print()
{
cout<<"Printing with derivedTwo's print function.baseVarible = "<< base::baseVariable<<endl;
}
};
int main()
{
base *obj1=new derivedOne(5);
base *obj2=new derivedTwo(7);
obj1->print();
obj2->print();
return 0;
}
I guess that is what you are asking for.
This is quite an old one, but perhaps another try at explaining Polymorphic Assignment (taken from Introduction to Design Patterns in CPP with Qt 2nd Edition by Alan Ezust, Paul Ezust)
Lets say you have an abstract base class:
class Shape {
public:
virtual double area() = 0;
virtual QString getName() = 0;
virtual QString getDimensions() = 0;
virtual ~Shape() {}
};
And you have two classes that inherits from this base class:
class Rectangle : public Shape {
public:
Rectangle(double h, double w) : m_Height(h), m_Width(w) {}
double area();
QString getName();
QString getDimensions();
protected:
double m_Height, m_Width;
};
class Circle : public Shape {
public:
Circle(double r) : m_Radius(r) {}
double area();
QString getName();
QString getDimensions();
private:
double m_Radius;
};
And you have your main appilication:
#include "shapes.h"
#include <QString>
#include <QDebug>
void showNameAndArea(Shape* pshp) {
qDebug() << pshp->getName() << " " << pshp->getDimensions()
<< " area= " << pshp->area();
}
int main() {
Rectangle rectangle(4.1, 5.2);
Circle circle(6.1);
showNameAndArea(&rectangle);
showNameAndArea(&circle);
return 0;
}
In the global function showNameAndArea, the base class pointer, pshp, is successively given the addresses of objects of the three subclasses. For each address assignment, pshp polymorphically invokes the correct getName and area functions of the Rectangle and Circle classes.
精彩评论