Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Created April 12, 2017 17:56
Show Gist options
  • Save tornikegomareli/8da8c0a2e55540c37bc488dac3a670e6 to your computer and use it in GitHub Desktop.
Save tornikegomareli/8da8c0a2e55540c37bc488dac3a670e6 to your computer and use it in GitHub Desktop.
How Copy Constructor works and Why we need it
#include <string>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Person
{
private:
string *name;
int age;
public:
Person() = default;
Person(string name, int age)
{
cout << " Overloaded constructor was called \n";
this->name = new string(name);
this->age = age;
}
Person(const Person &object)
{
cout << " Copy constructor was called \n";
this->name = new string(*object.name); // this will make new instance
this->age = object.age;
}
void UpdateInformation(string name, int age)
{
*(this->name) = name;
this->age = age;
}
void Introduce()
{
cout << "My name is " << *name << " and my age is " << age << endl;
}
~Person()
{
// delete[] name; we dont need delete it until we overload assignment operator
cout << "Object Deleted " << endl;
}
};
void display(Person object) // this will call copy constructor
{
Person sxva("giorgi", 30);
object.Introduce();
}
int main() {
Person Tornike("Tornike", 22); // this will call overload constructor
Person Daviti = Tornike; // this will call copy constructor
cin.get();
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment