Search code examples
c++initialization-list

c++ self in initialisation list


i have this code snippet

class Osoba{
         Osoba(char* imie,int wiek){                         
                     this->imie=new char[strlen(imie)+1];
                     strcpy(this->imie,imie);
                     this->wiek=wiek;
                     cout<<"Utworzono Osobe "<<this->imie<<endl;
         }
         Osoba(Osoba& x){
                 Osoba(x.imie,x.wiek);
         }
[...]

and when i call the copy constructor it doesnt work (creates and destroyes object).

Edit: if i use

         Osoba(Osoba& x): Osoba(x.imie,x.wiek){

i get type 'class Osoba' is not a direct base of 'Osoba'

how is this done ?


Solution

  • You cannot call a constructor except for creating another different object.

    If you need to have some code in common between constructors you can place it in a separate method and call that method. Note that in the constructor you can call methods of the object but virtual methods are not going to dispatch do derived classes.

    In other words if you have

    struct Foo
    {
        virtual void doit() { ... }
        Foo() {
            doit();
        }
    };
    
    struct Bar : Foo
    {
        virtual void doit() { ... }
    };
    

    during the constructor of Bar the implementation of doit called will be the one defined in Foo because during the constructor of the base part of the derived object, the object is only a "base" object. Only at the end of the constructor it becomes a "derived" object right before executing any eventually present code in the "derived" constructor.

    Be careful that other object oriented languages use a different approach...

    For an explanation of what happens exactly in C++ see this article.

    If you like instead a legalese description this is what is stated in the C++ standard at 12.7.4:

    Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object (1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expression refers to the object under construction or destruction but its type is neither the constructor or destructor’s own class or one of its bases, the result of the call is undefined.