Skip to content

Instantly share code, notes, and snippets.

@klemens
Created October 6, 2013 15:11
Show Gist options
  • Save klemens/6855206 to your computer and use it in GitHub Desktop.
Save klemens/6855206 to your computer and use it in GitHub Desktop.
Directly access private data members in copy constructor
/**
* Compiles without error using g++ 4.8.0
* g++ -Wall -Wextra -Werror -pedantic -o copyTest copyTest.cpp
*/
#include <iostream>
class Person {
public:
Person(std::string name) {
this->name = new std::string(name);
}
~Person() {
delete name;
}
Person(const Person& rhs) {
// here we directly access the private member name of rhs
this->name = new std::string(*(rhs.name));
}
void sayName() {
std::cout << *name << std::endl;
}
private:
std::string* name;
};
int main() {
Person p1("p1");
Person p2(p1);
p2.sayName();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment