constructor calling

A

asit

Can i call constructor and destructor using object name and dot
operator ??

#include <iostream>

using namespace std;

class my_cls
{
int a;
public:
my_cls()
{
a=100;
cout<<"Constructor called"<<endl;
}
~my_cls()
{
cout<<"Destructor called"<<endl;
}

void put_data()
{
cout<<a<<endl;
}
};

int main()
{
my_cls a;
a.my_cls::my_cls();
return 0;
}

Is the above program legal ??
 
A

Alf P. Steinbach

* asit:
Can i call constructor and destructor using object name and dot
operator ??

#include <iostream>

using namespace std;

class my_cls
{
int a;
public:
my_cls()
{
a=100;
cout<<"Constructor called"<<endl;
}
~my_cls()
{
cout<<"Destructor called"<<endl;
}

void put_data()
{
cout<<a<<endl;
}
};

int main()
{
my_cls a;
a.my_cls::my_cls();
return 0;
}

Is the above program legal ??

Why don't you try it with your compiler? (Preferably one that does not have
"best before" 1998).


Cheers, & hth.,

- Alf
 
I

Ivan Vecerina

: Can i call constructor and destructor using object name and dot
: operator ??
It is legal to call the destructor directly, indeed.
But not the constructor - instead, you have to use the
placement-new syntax.

For instance:
T obj(1);
obj.~T(); //destroy the object
new (&obj) T(2); //NB: must first #include <new>

Note however that the above idiom cannot be made
exception safe, and should therefore not be used.

A better approach is to create a separate instance
and use a swap operation (implemented by the class).
For instance:
T obj(1);
T(2).swap(obj);
 

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
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top