Skip to content

J) Constructor: default, parametric, copy, move

kalinosia edited this page Mar 13, 2021 · 2 revisions

Default constructor

X()

Person(); You can add something in other file

Person(){}; "empty"

With some defined atributes

    Person():
    name("Unnamed"),
    age(0) {};

Parametric constructor

Person(const std::string& name, unsigned age):
name(name),
age(age) {};

Copy constructor

X(Xconst&other)

class Animal{
private:
    string name;
public:
    Animal() { cout << "Animal created. Constructor." << endl; }
    Animal(const Animal& other) :name(other.name) { cout << "Animal created by coping. Copy constr." << endl; }
                                                           //Can use: other.speak(); only if speak is const
    void setName(string nameSet) {this->name=nameSet;};
    void speak() const { cout << "My name is: " << name << endl; } //const prevent name="Julian";
    
    ~Animal(){ cout<<"Destructor"<<endl;} //Destructor
}

int main(){
    Animal dog;
    dog.setName("Bobby");
    dog.speak();
 
    Animal cat = dog; //COPY
    cat.speak();

    Animal mouse(cat); //COPY
}

Move constructor

X(X&& other)

Person (Person&& other):
name(std::move(other.name),
age(std::move(other.age){};

USE: Animal secondDog = move(firstDog);

Clone this wiki locally