Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Pointers and Pure Virtual Functions

Hello,

I have :-

class Shape
{
public:
Shape() { }
virtual ~Shape() { }
virtual void draw() = 0;
};

class Circle : public Shape
{
public:
Circle() { }
virtual ~Circle() { }
void draw() { cout << "Drawing Circle\n"; }
};

In main() I have :-

Circle c1;
c1.draw();

Circle *pc1 = new Circle;
pc1->draw();
delete pc1;

I understand that in the first instance I'm calling draw directly thru the object and on the second one thru the pointer. However, a pointer is "an address of another variable". How does this definition fiting to this code ?

Thanks,

Imanuel.
[742 byte] By [ami] at [2007-11-11 10:00:01]
# 1 Re: Pointers and Pure Virtual Functions
pc1-> means you are de-referencing the pointers which is nothing but c1.draw()
venkat78 at 2007-11-11 20:59:42 >
# 2 Re: Pointers and Pure Virtual Functions
Modify your working definition of a pointer.

You might also refine your thinking about what a "variable" is: a name for a memory location, just as a pointer is. What is different is what the memory location referred to by that name contains.

A pointer is a memory location which contains the address of another memory location ... and one of many things can existed at that "referenced" or "pointed to" memory location. One of the things that might be accessed through the memory address held in the pointer can be a "variable" - the location of memory containing the value of some data field. Another of those many things can be the base address of a dynamically created object of class Circle, just as your pointer pc1 does. The -> then dereferences the address where that class's draw function is defined so that your program can call and have that function executed.
nspils at 2007-11-11 21:00:37 >
# 3 Re: Pointers and Pure Virtual Functions
pc1-> means you are de-referencing the pointers which is nothing but c1.draw()
Not quite. There is a substantial difference between calling draw through a pointer and calling it directly for an object. In the former case, you guarantee that the call is polymophic. I.e., the call is resolved at runtime of if pf happend to be pointing an object derived from Shape, the "right" draw will be selected. In the case of obj.draw() the call is resolved at compile time, never at runtime.
The main purpose for using pointers to objects is polymorphism. No matter what the static type of pf is (in this case: Shape*), you can bind to it at runtime any object that is publicly derived from Shape. This dyanmic binding mechanism has a price though: the call is resolved at runtime, which means that it's slightly slower (in some cases) than a statically-resolved call.
Danny at 2007-11-11 21:01:41 >