Defining an object with a pointer to an object and operator new in c++ -


this question has answer here:

simple example regarding definition of objects pointer object. define object a *a = new a(123.4); , 1 a *b = new a(*a);

what not understand how work b(pointer to) object? how copy constructor kicks in here , initializes value same object a? thought work, should declare custom copy constructor in class.

#include <iostream> using namespace std;  class { public:     a(float v) { a::v = v; }     float v;     float set(float v) {         a::v = v;         return v;     }     float get(float v) {         return a::v;     } };  int main() {     *a = new a(123.4);     *b = new a(*a);      cout << a->v << endl;     cout << b->v << endl;      a->v = 0.0;     cout << a->v << endl;     cout << b->v << endl;      b->v = 1.0;     cout << a->v << endl;     cout << b->v << endl;      return 0; } 

the program's output is:

123.4 123.4 0 123.4 0 1 

thanks in advance.

the compiler generated copy constructor you. perform shallow copy of member variables, enough in case.

from wikipedia:

special member functions in c++ functions compiler automatically generate if used, not declared explicitly programmer. special member functions are:

  • default constructor (if no other constructor explicitly declared)
  • copy constructor if no move constructor or move assignment operator explicitly declared. if destructor declared, generation of copy constructor deprecated.
  • move constructor if no copy constructor, move assignment operator or destructor explicitly declared.
  • copy assignment operator if no move constructor or move assignment operator explicitly declared. if destructor declared, generation of copy assignment operator deprecated.
  • move assignment operator if no copy constructor, copy assignment operator or destructor explicitly declared.
  • destructor

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -