Click to See Complete Forum and Search --> : pointers to classes


sattenapalli
November 17th, 2004, 05:38 AM
Base class pointer can point to derived class object .But derived class pointer can not point to Base class object.WHY?

Brane
November 17th, 2004, 06:14 AM
Base class doesn't have all functions and variables which derived class implements, so if you point derived pointer to base class some functions and variables of pointer can't point to actual memmory of object.

Ajay Vijay
November 17th, 2004, 06:23 AM
For clarification about this issue, just consider:class Base
{
data1,data2;
func1;
};
class Der: public Base
{
data 3;
func2, func3;
};Further we have object of "Base" and pointer to "Der":Base b;
Der *pd;
pd=&b; // Assume it is correct
// Or we may use dynamic_cast or C-style cast for compiler satisfaction.

// will these statements work correctly? (assume it will compile correctly)
pd->d3=400;
pd->func3();

sattenapalli
November 17th, 2004, 06:27 AM
hi Brane.I got your point but there is a problem.you told that derived class contains some extra members,apart from those inherited from base class.So we can not point derived class pointer to base class as these members are not available in base.SIMILARLY base class contains some members that can not be inherited to derived class,example private members.But we can point a base class pointer to derived class.WHY?

Ajay Vijay
November 17th, 2004, 06:50 AM
Despite the public/protected/private fact, all data members are inherited from the base class, even they are not accessible by derived class. Try using sizeof with the derived object and it will return TOTAL bytes used by the class object.

In reality, a pointer (or reference) points only to the first byte of class (i.e. base offset of object) not to "entire" object.

sattenapalli
November 17th, 2004, 07:06 AM
I did not get you ajay vijay.If we use sizeof()operator it gives total size of variables only not functions because functions are common to all objects.Then how do I knoe they are inherited but not accessible.Please be clear about it.I am beginner

Ajay Vijay
November 17th, 2004, 07:14 AM
class A
{
int a;
public:
int b;
... functions
};
class B: public A
{
public:
int c;
};
Now if we declare object of type B, its size would be 12 (assuming, 32-bit integer), despite the fact that we cannot access A::a.

Furthermore, I said to sizeof on object and not on pointer. If you sizeof on pointer it will return 2/4 depending on platform. In that case, you may use sizeof(*pObject).

I think I made some clarification to you. Post reply on any confusion.

Ajay Vijay
November 17th, 2004, 07:16 AM
Yes, functions do not count on object's size. Only virtual function table pointer (vptr) counts -- that you will get when you read C++ more... :thumb: