Coding Problem, Help Needed

B

batista

Hello to ALL,

I'll explain my problem by pseudo code

class A
{
int x;
char y;
string z;
}

class B
{
GetVariable(int i)
{
A a = new A();
//Now I want to return the ith varaible
//of class A
}
}

class C
{
GetVar()
{
B b = new B();
b.GetVariable(0) //it shud return x
b.GetVariable(1) //it shud return y
b.GetVariable(2) //it shud return z
}
}

Now how do I implement the GetVariable(int i), in VC++
The reason I have class B is because there are lot's of classes
like class A, and i don't want to edit them all.

Any Suggestions...

Thanks In advance...
Cheers...

Bye
 
W

William DePalo [MVP VC++]

batista said:
Hello to ALL,

I'll explain my problem by pseudo code

class A
{
int x;
char y;
string z;
}

class B
{
GetVariable(int i)
{
A a = new A();
//Now I want to return the ith varaible
//of class A
}
}

class C
{
GetVar()
{
B b = new B();
b.GetVariable(0) //it shud return x
b.GetVariable(1) //it shud return y
b.GetVariable(2) //it shud return z
}
}

Now how do I implement the GetVariable(int i), in VC++
The reason I have class B is because there are lot's of classes
like class A, and i don't want to edit them all.

Any Suggestions...

x, y, and z are private to A. So you need public accessor functions in A or
you need to make B a friend of A.

Regards,
Will
 
T

Tamas Demjen

C++ is a strongly typed language. You can't write a function that
returns different types based on its input argument. The only way is to
use a variant type. There are many existing implementations, or you can
write your own. The key is to write a class that can change its type
dynamically. The easiest way is using a union:

struct MyVariant
{
enum VarType { IntType, CharType, StringType };
VarType type;
union
{
int i;
char c;
char* s;
};
};

Of course this is unfinished, but it gets you started. Take a look at
the VARIANT data type in COM, although it's pure C, it also has a C++
wrapper in ATL.

Note that variants introduce complexity and runtime overhead to your
code. Obviously a GetVariable function like yours will run way slower
than accessing x, y, and z directly.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top