Memory Allocation ?

is this a valid call first knowing CPolygon is an Abstract base class with virtual function "int area(void) = 0" and CRectangle is a derived class returning the area.

CPolygon *poly1 = new CRectangle();

i understand its kind of confusing what im asking but its based off of pg 111 in the slides provided by this website on c++.

If you can help and explain what that is if it does work that would be great.

Thank you for your time
What is the question?
whoops sorry,
is the line
CPolygon *poly1 = new CRectangle(); valid and if so what does it do?
my prof just threw some stuff about abstract base classes which was cool, but then had this in the main function with
poly1 -> printarea()

and said "There can be no CPolygon, it is abstract and defines an interface"

Yes, since cRectangle derives from cPolygon and cRectangle is a cPolygon.

The reason why this is important arises when you want a collection of of objects. All these objects share the same properties, but differ in some specific respect.

In this case cRectangle is a specific type of polygon which requires a specific call to area to determine the area.
This line creates an object of type CRectangle in the heap and assigns the address of the object to the pointer of type CPolygon.
So if you will access the object through this pointer the object will be interpreted as an object of type CPolygon. That means that you can only those methods that were defined for class CPolygon. But becuase function area is virtual then when you will call it the following way


then instead of function area declared in class CPolygon function area defined in class CRectangle will be used.
so the new CRectangle() uses CRectangle to create an object from the method CRectangle?

or am I just confusing myself.

And cant you use the methods in CPolygon already since CRectangle inherits CPolygons methods?

also thank you for helping !
or do objects refer to functions as well?
CRectangle is not an abstract class so you can create objects of this class. You only assign address of the created CRectangle object to pointer of type CPolygon. Now if you will use this pointer that is of type CPolygon you can call only those methods that were defined in class CPolygon because the static type of the pointer is CPolygon *
okay i defiantly understand it more now.

thank you for all your help !
Topic archived. No new replies allowed.