Skip to main content
gamedev.net
🔒 Locked

Simple constructor question (C++)

Started by Red Ant Jun 29, 2004 at 7:33 AM 4 replies 700+ views
Original Post
Red Ant
Red Ant

class A
{
private:
    void init();
public:
    A();
    A( const A& rSource );
....
};

void A::init()
{
    // do stuff
}

A::A()
{
    init();
}

A::A( const A& rSource ) : A()
{
    // copy rSource or whatever
}
Is this: A::A( const A& rSource ) : A() legal? Meaning, will this invoke the default c'tor (and thus properly initialize the object) before doing the actual copy c'tor stuff? Haven't got a compiler here, so I can't try it out right now. :P Regards, Red Ant
Agony
Agony
I don't think it works. Constructor calls in the initializer list must be either base class constructors, or member object constructors. At least, that's what I've always thought, and that's what MSVC6 enforces. Would be kinda nice if it were allowed, though. Might be a bit inefficient at times, but still convenient.
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
DrPizza
DrPizza
Sadly not.
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;} /*** drpizza@battleaxe.net ***/
Red Ant
Red Ant
Oh ... too bad. Ah well, thanks anyway!
TangentZ
TangentZ
Quote:
Original post by Red Ant
Is this: A::A( const A& rSource ) : A() legal? Meaning, will this invoke the default c'tor (and thus properly initialize the object) before doing the actual copy c'tor stuff?


That is not legal.

What you could do, though, is something like this.

class A    {    private:        X x;    public:        A() : x() { }        A(const A &other) : x(other.x) { }        // A(const A &other) { x = other.x; }  // Inefficient!    };// end


If X is costly to construct, you would want this anyway (invoke
the copy-constructor of X).

You wouldn't want to construct X and then copy X.
神はサイコロを振らない!
Red Ant
Red Ant
Good point, TangentZ, but then I usually write my copy methods more like:

x.copy( other.x ) rather than x = other.x; anyway. If that makes sense. :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.