copy constructor

Mar 28, 2012 at 4:52pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class P {
  public:
      P() {}
      ~P() {}

      P(P const & p) {      //<--- Question 1
          setX(p.getX());   //<--- Question 2
          setX(p.x);        //<--- Question 3
          x = p.x;          //<--- Question 3
      }

      void setX(int i) {
          x = i;
      }

      int getX() {
          return x;
      }

  private:
      int x;
};


Question 1 Whats the difference between P(P const & p) and P(const P & p) ?
Question 2 Why this does not work ?
Question 3 Why does this work, (accessing the private data memeber directly) ?
Mar 28, 2012 at 4:59pm
Q1. There is no difference between these two declarations.
Q2. It does not work because you are trying to call non-const member function for const object (because you declared the parameter as a const reference). If you will rewrite function getX as

1
2
3
4
int getX() const
{
          return x;
}


it will work.

Q3. It works because the objedts are of the same type.
Last edited on Mar 28, 2012 at 5:01pm
Mar 28, 2012 at 4:59pm
Answer 1 There is no difference
Answer 2 Because getX is not const so you can only call it on non-const objects. If you define getX as this it will work
1
2
3
int getX() const {
	return x;
}

Answer 3 Because all member functions of P has access to the private member's of P.
Last edited on Mar 28, 2012 at 5:00pm
Mar 28, 2012 at 5:08pm
@vlad from moscow
@Peter87


Thank you


Can I use

1
2
3
int const getX() {
	return x;
}


or

1
2
3
const int getX() {
	return x;
}


instead of

1
2
3
int getX() const {
	return x;
}
Mar 28, 2012 at 5:18pm
No. The first two has return type const int.
Mar 28, 2012 at 5:31pm
In the declaration

int getX() const;

const belongs to the implicit object parameter this as if you would declare

int getX( const P * );
Mar 28, 2012 at 6:43pm
I think I got it, let me experiment around, then will get back.
@vlad from moscow
@Peter87

Thank you for your help
Apr 2, 2012 at 3:55pm
So let me put down my understanding for the help of any one like me.

In a same class i.e

Same class
Derived class
Friend class

you can access the private members of that class i.e

Same class
Parent class
Base class
Last edited on Apr 2, 2012 at 4:03pm
Apr 2, 2012 at 4:00pm
C++ is just very strict about the type

if you tell it that you will get return_type / argument_type , then the function must return the exact return_type / argument_type, for C++

type != const type
Topic archived. No new replies allowed.