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 IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Abt.. Referring Subclass members thru base class object

Status
Not open for further replies.

arul77

Technical User
May 24, 2001
6
IN
class one {
public :
int a;
};

class two :public one{
public:
int d;
}

class test {
union{
one a;
};
};

int main(){

test obj;
obj.a.d=10;
printf("%d",a.d);
return 0;
}

My problem is i need to have a class object in an union,[since there is a rule that union cannot contain members with constructors], so i created a dummy class one to overcome this,..

Error:
undefined variable d.
how to solve this...

 
Well, either is a typO, either you were not paying attention, but inside the union, you have the class ONE which has NO MEMBER d...
It should work if you switch it to class two! [red]Nosferatu[/red]
We are what we eat...
There's no such thing as free meal...
once stated: methane@personal.ro
 
let use subclass with virtual data access methods instead of unions:

#include <stdio.h>

class one {
public :
int virtual GetData(void) = NULL;
void virtual PutData(int iData) = NULL;
};

class two :public one {
public:
int d;

int virtual GetData(void);
void virtual PutData(int iData);
};

int two::GetData(void)
{
return(d);
}

void two::putData(int iData)
{
d=iData;
}

class test {
public:
one *one_ptr;
};

int main(){

test obj;
two act_data;

obj.one_ptr=(one *)&act_data;

obj.one_ptr->PutData(10);
printf(&quot;%d&quot;,act_data.d);

return 0;
}
 
mingis is correct. Take full advantage of the polymorphism with pointers. class two IS-A class one. By declaring the class as a specific type (no pointer) you can NOT assign any child class to it where as with a pointer, you get complete diversity.

Matt
 
All

Tx for your efforts..

I will use this solution
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top