Not sure if someone has already asked this, but I see a strange behavior here:
I've declared two classes, one base and one derived with just one virtual method display()
.
class A {
public:
virtual void display() {
cout << "base class" << endl;
}
};
class B:public A {
public:
void display() {
cout << "derived class" << endl;
}
};
Now, in main()
, if I try to declare an auto_ptr
of A
and assign it a new instance of B
,
int main() {
auto_ptr<A> *a = (auto_ptr<A>*)new B();
a->display();
}
I get this error on compiling:
"
'class std::auto_ptr<A>'
has no member named 'display'"
Am I doing something wrong? Can someone explain the behavior?
You are creating a pointer to an
auto_ptr
. Anauto_ptr
is an object that works like a pointer, so you don't need to add a*
.You probably want:
Although I must recomment either Boost's smart pointers (
scoped_ptr
andshared_ptr
) or C++11'sstd::unique_ptr
andstd::shared_ptr
.