overloading constructor

G

gerhard321

Hy!

why doesn't work this?
the problem is, if i create an object
User *u= new User(5);
my object doesn't get initialised, but if i call
User *u = new User(5,"foo","foo");
everything works fine the code looks like this:

User::User(DPNID UserIdentifier)
{
// your code here
User(UserIdentifier,"unnamed");
}


User::User(DPNID UserIdentifier, CString UserName)
{
// your code here
User(UserIdentifier,UserName,"unknown");
}


User::User(DPNID UserIdentifier, CString UserName, CString Status)
{
// your code here
m_UserIdentifier=UserIdentifier;
m_UserName=UserName;
m_Status=Status;

// real init beginns here
m_ID=++m_InstanceCounter;
m_CreationTime=CTime::GetCurrentTime();;
}
 
M

msalters

(e-mail address removed) schreef:
Hy!

why doesn't work this?
User::User(DPNID UserIdentifier)
{
// your code here
User(UserIdentifier,"unnamed");
}

The User(UserIdentifier,"unnamed"); statement creates a
temporary User object. You can assign that object to *this,
but that would be an ugly hack.

The better solution is a default argument:
class User {
User(DPNID UserIdentifier, std::string name = "unnamed);
//...
};

HTH,
Michiel Salters
 
R

ravinderthakur

logically you cannot call a constructor in another construct. it dosn't
do what you are supposing it is doing.

this is unlike java where the same can be done!!!

thanks
ravinder.
 
D

David Hilsee

Hy!

why doesn't work this?
the problem is, if i create an object
User *u= new User(5);
my object doesn't get initialised, but if i call
User *u = new User(5,"foo","foo");
everything works fine the code looks like this:

User::User(DPNID UserIdentifier)
{
// your code here
User(UserIdentifier,"unnamed");
}


User::User(DPNID UserIdentifier, CString UserName)
{
// your code here
User(UserIdentifier,UserName,"unknown");
}


User::User(DPNID UserIdentifier, CString UserName, CString Status)
{
// your code here
m_UserIdentifier=UserIdentifier;
m_UserName=UserName;
m_Status=Status;

// real init beginns here
m_ID=++m_InstanceCounter;
m_CreationTime=CTime::GetCurrentTime();;
}

You can read about this in the FAQ (http://www.parashift.com/c++-faq-lite/)
in section 10 ("Constructors"), question 3 ("Can one constructor of a class
call another constructor of the same class to initialize the this object?").
 

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
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top