XMarshall
XMarshall

Reputation: 971

std::auto_ptr error

For the below C++ code, I am getting an compiler error:

class Mkt
{
    int k;
public:
    Mkt(int n): k(n)
    {
        throw;
    }
    ~Mkt()
    {
        cout<<"\n\nINSIDE Mkt DTOR function:\t"<<endl;
    }
    void func1()
    {
        cout<<"\n\nINSIDE FUNC1 function....value of k is:\t"<<k<<endl;
    }
};

int main(int argc, char* argv[] )
{
    try
    {
        std::auto_ptr<Mkt> obj(new Mkt(10)); //no implicit conversion
            obj.func1(); //error C2039: 'func1' : is not a member of 'std::auto_ptr<_Ty>'
    }
    catch(...)
    {
        cout<<"\n\nINSIDE EXCEPTION HANDLER..........."<<endl;
    }
return 0;
}

I am not able to understand why I am getting the error C2039? I am using VS 2008 compiler.

Pls help. Thanks

Upvotes: 3

Views: 2182

Answers (4)

Pooh
Pooh

Reputation: 21

This is very basic thing in c++ .. auto_ptr - the "ptr" stands for "pointer",

Upvotes: 1

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12403

Be aware that after you fix the compilation problem (change dot-operator into -> operator) you will encounter a huge run-time problem.

Mkt(int n): k(n)
{
    throw;
}

throw without an argument is meant to be used inside catch-blocks and causes re-throwing handled exception. Called outside catch-blocks will result in a call to abort function and your program termination. You probably meant something like

throw std::exception();

or, better,

throw AnExceptionDefinedByYou();

Upvotes: 2

sharptooth
sharptooth

Reputation: 170499

You have to use ->

obj->func1();

auto_ptr doesn't have func1(), but it has operator ->() that will yield a Mkt* pointer stored inside and then -> will be used again on that pointer and this will call the Mkt::func1() member function.

Upvotes: 5

Kiril Kirov
Kiril Kirov

Reputation: 38173

It is auto_ptr, this means, that it is pointer :). You must use operator->:

obj->func1();

Upvotes: 6

Related Questions