Originally Posted by
laserlight
It would be better for you to make your examples a bit more concrete (e.g., instead of "..." have say, an empty parameter list and a function body that prints a message identifying the function called) such that you can write a program to find out. Of course, due to possible undefined behaviour (e.g., if you tried to use new/delete since your base class does not have virtual destructor) you might still not be sure, but that's when you can present us with your program and your research and ask for confirmation (e.g., this looks right, this is why I think it works, am I correct?) or explanation (why do I get this compile warning/error?).
My question was more abstract. To put it in simple words: if I have a base class and a derived class from it. Then I defined a pointer that points to an object of the base class, could I access the members of the derived class using this pointer? (The answer turned out to be no from the following program I tried).
With same logic, if I defined a pointer that points to an object of the derived class, can I access the members of the base class using this pointer? (The answer turned out to be yes from the following program I tried).
The program is:
Code:
#include<iostream>
using namespace std;
class CPolygon
{
protected:
int height, width;
public:
void set_values(int a, int b) { height = a; width = b; }
};
class CRectangle:public CPolygon
{
public:
int area() { return height*width; }
};
class CTriangle:public CPolygon
{
public:
int area() { return height*width / 2; }
};
int main()
{
CRectangle rect1, rect2,*rectp;
CTriangle tri1, tri2,*trip;
CPolygon *polyp1, *polyp2;
polyp1 = &rect1;
polyp2 = &tri1;
rectp = &rect2;
trip = &tri2;
polyp1->set_values(3, 4);
polyp2->set_values(3, 4);
rectp->set_values(6, 8);
trip->set_values(6, 8);
/*rect.set_values(3, 4);
tri.set_values(3, 4);*/
cout << "The area of the rectangle 1 is: " << rect1.area() << endl;
cout << "The area of the triangle 1 is: " << tri1.area() << endl;
//cout << "The area of the rectangle 1 is: " << polyp1->area() << endl;
//cout << "The area of the triangle 1 is: " << polyp2->area() << endl;
cout << "The area of the rectangle 2 is: " << rectp->area() << endl;
cout << "The area of the triangle 2 is: " << trip->area() << endl;
system("pause");
return 0;
}
Any further comment on this is welcome.
Thanks