Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Pointer to Parent instance

Status
Not open for further replies.

noodles1

Programmer
Oct 31, 2001
58
If I have a pointer to an instance of a class, can I easily obtain a pointer to the instance of the parent class of that class?

An an example, if I have a class X that has as its parent, class Y, in a method for class X, I can access the pointer to the instance of class X via the keyword "this". Am I able to access a pointer to the instance of class Y that is created when the instance of X is created. Or is no specific instance of class Y created, even though the class Y constructor is called as a result of the constructor of class X?

 
Not sure I follow you.

class A
{
..
}

class B : A
{
..
}

class B inherits from A, so you can access anything A has via B

Or are you just trying to get the class of the parent?

K
 
I'm really trying to get a pointer to the instance of the parent class.

Using your example, if an instance of Class B is created, I'm assuming that an instance of Class A is also created that is accessible via the pointer to that instance of Class B.
 
The instance of class B is-an instance of class A. There is only one object. The this pointer inside B can be used as a pointer to A. As Kalisto said, you can access anything A has while inside of B. This is true of anything that is public or protected inside of A.
 
If you have
Code:
class A {};
class B {};
class C: public A, public B
{
};

C* see = new C;
A* eh  = static_cast <A*>(see);
B* bee = static_cast <B*>(see);
If you examine the addresses of eh and bee, one of them will be different from see.
 
And if you want to access anything in the parent class specifically, just call the function with the class name and scope resolution operator

Code:
void CMyClass::DoSomething()
{
  //might want to call base class's function first
  CTheirClass::DoSomething();
  //now do the rest of the code
}

this is the way ClassWizard does it also. So when you call the superclass's member instead of your own (as shown above), it's equivalent to using the 'this' pointer for the superclass


bdiamond
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top