Re: initializing a class using upcasted object
tom wrote:
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:
You're right. It does not compile at gcc too.
I've cut too much code before posting, anyway, here is the code (a minor
modification of yours) that compiles, but is wrong, could you test it
please? And is it a bug in gcc, or I'm missing something? (probably the
latter...)
#include <iostream>
using namespace std;
class Base {
public:
Base() {}
virtual ~Base() {}
virtual void foo() const =0;
};
class Der1 : public Base {
public:
Der1(int a,int b):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[])
int main()
{
Der1 temp(2,4);
X x(temp);
X x1(Der1(4,6)); // no error in gcc
x.complicated_function_that_uses_foo();
x1.complicated_function_that_uses_foo(); //here the progam
// exits with "pure virtual method called"
return 0;
}
#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;
}
--
mati