creating a pointer to a base class

J

john smith

Hi, I'm trying to do something like this:

class A {
public:
virtual void f() {
// do something
}
};
class B : public A {
// some methods here
};

class C {
public:
C(A* a)
{
a_ = new WHAT?!?! // could be either A or B!!
}
A* a_;
};

In general, there could be more classes derived from A or B.... Assuming
there are copy constructors and assignment operator defined for A and B.
How can I initalize a_? do I have to resort to RTTI if-else ladders!?
There is got to be a better way!

thanks

Smith
 
K

Karl Heinz Buchegger

eftewuer said:
Maybe You should write the "clone function for every class (A and B). In
class A
A* A::clone()
{
A* aa = new A();
//copy members variables to aa;
return aa;
}

A* A::clone()
{
return new A( *this );
}

is simpler and less error prone.
 
E

eftewuer

U¿ytkownik "john smith said:
Hi, I'm trying to do something like this:

class A {
public:
virtual void f() {
// do something
}
};
class B : public A {
// some methods here
};

class C {
public:
C(A* a)
{
a_ = new WHAT?!?! // could be either A or B!!
}
A* a_;
};

In general, there could be more classes derived from A or B.... Assuming
there are copy constructors and assignment operator defined for A and B.
How can I initalize a_? do I have to resort to RTTI if-else ladders!?
There is got to be a better way!

Maybe You should write the "clone function for every class (A and B). In
class A
A* A::clone()
{
A* aa = new A();
//copy members variables to aa;
return aa;
}

In class B
B* B::clone()
{
B* bb = new B();
//copy members variables to bb;
return bb;
}

And inyour class C
C::C(A* a)
{
a_ = a.clone();
}
 

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

Members online

No members online now.

Forum statistics

Threads
474,138
Messages
2,570,804
Members
47,349
Latest member
jojonoy597

Latest Threads

Top