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;
};

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

Bad Post

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.

thanks, it works now :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.