mercredi 4 septembre 2019

Assigning same-type-objects having string as data member with no copy constructor

string, which is basically dynamically allocated, therefor on heap, is found in the following object. When initializing that object with no copy constructor, how is it possible that it creates a deep copy of it?

Plus, how is it possible that in the line

include

using namespace std;

class A{

string sa;

public:

A(string r): sa(r){}

virtual ~A(){}

virtual string operator*() {return sa;}

};

class B: public A{

string sb;

public:

B(string x, string y): A(x), sb(y){}

virtual ~B() {}

virtual string operator*() { return A::operator*()+" " +sb;}

};

int main() {

A* pa = new B("John Joseph", "Nicholson");

**A sa = *pa;**

cout << *sa << " " << *(*pa) << endl;

return 0;

}

The output is: "John Joseph John Joseph Nicholson"

I would expect the output would be quite of a gibberish, as I thought that when creating "A sa = *pa", it will call the copy constructor for initalization, yet, there is none, therefor shallow copy will be given.

Plus, how is it possible to even print an instance in this form? Is it the fact that the fields are only string?

Thanks and sorry for my noobiness.

Aucun commentaire:

Enregistrer un commentaire