0
#include <iostream> int main(void) { class date { private: int day; int month; int year; public: date( ) { std::cout << "default constructor called" << std::endl; } date& operator=(const date& a) { std::cout << "copy constructor called" << std::endl; day=a.day; month=a.month; year=a.year; } date(int d ,int m ,int y ) : day(d),month(m),year(y){ std::cout << "constructor called" << std::endl; } void p_date(){ std::cout << "day=" << day << ",month=" << month << ",year=" << year << std::endl; } date& add_day(int d) { day += d; return *this;} date& add_month(int d) { month += d;return *this; } date& add_year(int d) { year += d;return *this; } }; class cdate { date n; public: cdate(date b) : n(b) { std::cout << "cdate constructor called" << std::endl;} void p_cdate() { n.p_date(); } }; cdate ncdate(date(30,1,2012)); ncdate.p_cdate(); } 

When we instantiate ncdate in this code:

  1. temporary date object created when we call cdate ncdate(date(30,1,2012));
  2. then i expect the call n = b and expect n's copy constructor to be called.

n's copy constructor is not getting called and i cant figure out why. I know there is something wrong in the 2nd assumption. Note: this is test code only so don't go over its performance, usability etc.

3 Answers 3

5

You have not defined a copy constructor for date, so the implicitly-declared copy constructor is used.

A copy constructor would look like date(date const& other) { }. You have provided a default constructor (date()) and a copy assignment operator (date& operator=(const date& a)). Neither of these is the copy constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

1. I am definitely sleepy. I misunderstood date& operator=(const date& a) to copy constructor. 2. WOW! people are really live on this website. Like the prompt response. thanks
0

actually, I do not found the copy constructor in your code. the copy constructor shall declare as date(date& d), you only declare a assignment operation.

Comments

0

This is not a copy constructor, but operator=.

date& operator=(const date& a) { std::cout << "copy constructor called" << std::endl; day=a.day; month=a.month; year=a.year; } 

A copy constructor would look like this:

date(const date& a) { /*... */ } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.