Created
October 6, 2013 15:11
-
-
Save klemens/6855206 to your computer and use it in GitHub Desktop.
Directly access private data members in copy constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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