emufossum13
emufossum13

Reputation: 407

Is this a type of constructor?

I was looking through a c++ book I have, and I found this example of code

class CDistance
{
private:
    int feet, inches;
public:
    CDistance();
    CDistance(int, int);
    ~CDistance();
    void setDist();
    void printDist() const;
    CDistance add(const CDistance&) const;
};

I understand Constructors and overloading and that kind of thing, but what about this prototype on the bottom that's of the class type. The book, strangely enough, didn't give any information on it, just the diagram. But I was just wondering, what does it mean that the function type is of the class. I'm pretty sure I understand the parameter, as it seems to be a constant reference to an object of that class type. But why/how could you declare a function like that, does it mean that it returns the class? Lol, I'm new to programming, and if someone could help me understand this, I would really appreciate it.

Upvotes: 0

Views: 114

Answers (4)

cosinus0
cosinus0

Reputation: 613

It is useful:

CDistance D1 = CDistance();

CDistance D2 = CDistance();

CDistance D3 = CDistance();

D3.add( D2.add(D1) );

Upvotes: 0

RicoWijaya
RicoWijaya

Reputation: 15

did you mean : CDistance add(const CDistance&) const;?

this is the detail :

  1. the purpose of const in the parameter is to make sure that the original object must not be changed via its reference... the const after parameter is to ensure that the the method must not change anything in its body..

  2. that function return object of CDistance, so after the execution you can either use a new object to get it, as Example :

CDistance tempObj = theObj.add (param_obj);

hope that help... :D

Upvotes: 1

pmr
pmr

Reputation: 59831

Constructors are different from normal member functions in certain ways:

  • they don't have a return type
  • their name is the same as the class name
  • they cannot be const qualified

This makes the function CDistance::add not a constructor, because it fails on all 3.

Upvotes: 2

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

You call a function a constructor only if it has the name of the class. The function of type CDistance means that the function returns an object of the class. So it is not a constructor

Upvotes: 4

Related Questions