954,157 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

how to define a constructor with const members

Hello, I am having problem to define a constuctor of a class with private member which is also of a const type. When I try to compile it complains that the const members do not have initalized data. Hmm, anyway it works fine if I remove const. However is it possible to define a constructor with const members which is possible to set values to?

I know that const is values you can't change values on, but exercise says to use const. help is appreciated.:)

e.g. I want to create an object of a person

Bike bicycle (2, "Monark", "blue", 24.11);


and here is the constructor code

Bike::Bike(const int wheel, const string brand, string color, double wheelsize) {
    w = wheel;
    b = brand;
    c = color;
    ws = wheelsize;

}


and here is the class file

class Bike {
public:
    Bike (const int, const string, string, double);
private:
    const int w;
    const string b;
    string c;
    double ws;
};
ganmo
Light Poster
38 posts since Mar 2009
Reputation Points: 46
Solved Threads: 1
 

Try this:

class Bike {
public:
    Bike (const int, const string, string, double);
private:
    const int w;
    const string b;
    string c;
    double ws;
};
Bike::Bike(const int wheel, const string brand, string color, double wheelsize):
w(wheel),
b(brand),
c(color),
ws(wheelsize)
{}

It is generally better to write constructor using member initialization(what I did) rather than assignment(what you did).
This approach is more efficient.
why? because in this approach you are saving the overhead to create wheel,brand,color,wheelsize. Instead you are just using those value just to initialize your data members

siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,486
Solved Threads: 140
 

Bad Post

MatEpp
Junior Poster in Training
79 posts since Jan 2009
Reputation Points: 21
Solved Threads: 12
 

MatEpp>>The names, wheel, brand, etc. are missing from
[edit]This was posted in the post above. But Maybe he realised his fault and then removed this remark marking it as "Bad Post"[/edit]
That is a prototype of the constructor. It is perfectly fine.
It just tells the compiler that " you will find the definition of the constructor somewhere in the code below".
You usually omit the name of the formal parameters when declaring prototype.

siddhant3s
Practically a Posting Shark
816 posts since Oct 2007
Reputation Points: 1,486
Solved Threads: 140
 

thanks, it works now :)

ganmo
Light Poster
38 posts since Mar 2009
Reputation Points: 46
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You