Re: initializing a class using upcasted object
I don't know what you meant. I get your code compiled, and found that
the misused scenario you pointed out actually doesn't pass the
compilation, see the comment in the code below:
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {}
virtual void foo() const =0;
};
class Der1 : public Base {
public:
Der1():Base() { }
~Der1() {}
virtual void foo() const { cout<<"der1";}
};
class X {
const Base& ref;
public:
X(const Base& ref):ref(ref) {}
~X() {}
void complicated_function_that_uses_foo()
{
ref.foo();
};
};
int _tmain(int argc, _TCHAR* argv[])
{
Der1 temp;
X x(temp);
//X x(Der1()); //error: this line can't be compiled,
//in vs I got an error: C4930
x.complicated_function_that_uses_foo();
return 0;
}
On Jul 21, 8:43 pm, mati <longrai...@gazeta.NOSPAM.pl> wrote:
Hi
Here is the code:
class Base {
public:
Base() {...}
virtual ~Base() {}
virtual void foo() const =0;
};
class Der1 : public Base {
public:
Der():Base() {...}
~Der() {...}
void foo() const {...}
};
There are several Der.. classes, and the problem is that I want to make
some X class, that will have a handle to the Base, in order to use
polymorphism.
Initialization of X objects will determine which actual object in the
Base's hierarchy will be used (Der1 or Der2 or ..), but I have no idea
how to do that in "nice" way.
If I use references as the handle, I end with something like this:
class X {
const Base& ref;
public:
X(const Base& ref):ref(ref) {...}
~X() {...}
complicated_function_that_uses_foo();
};
But it must be used like that:
Der temp();
X x(temp);
x.complicated_function_that_uses_foo();
And it can be easily misused:
X x(Der());
x.complicated_function_that_uses_foo(); //calling pure virtual method
I thought about pointers, but pointers are evil.. erm, I mean that I
haven't came up with anything "nice" using pointers.
Any ideas on how it _should_ be done?
Thanks in advance.
--
mati