1
votes

Hi, I've created a class which has three constructors, two integer members & one const int member. So for one constructor I'm using initializer list to assign const int member but I am getting error in other two constructors

Here is my code:

class base
{
public:
    base();
    base(const int _count);
    base(int a ,int b);
    ~base();
protected:
    int m_ia , m_ib;
    const int count;
};
base::base()
{
}
base::base(const int _count):count(_count)
{
}
base::base(int a , int b)
{
    m_ia = a ;
    m_ib = b;

}
base::~base()
{

}
void main()
{
    base *obj2 = new base(1000);
    getchar();
}

Number of Errors:2

1.'base::count' : must be initialized in constructor base/member initializer list at base()

2.'base::count' : must be initialized in constructor base/member initializer list at base(int a ,int b)

3
... initialise count in the other 2 constructors in the same way... It doesn't automatically initialise it to 0 just because you didn't say anything.flight
void main is not legal. The return type must be int. Also, if base is supposed to be a base class, that destructor should be virtual. obj2 should also be a normal object in this example. Right now, it's leaking memory. Finally, why not use a constructor initializer list for your other members as well? There's really almost never any down side.chris

3 Answers

4
votes

You should probably make sure all your constructors are initializing all member variables, not just the one's being passed in as arguments. I'd rewrite your constructors as

base::base()
: m_ia()    // value initializes i.e. sets to 0
, m_ib()
, count()
{
}

base::base(const int _count)
: m_ia()
, m_ib()
,count(_count)
{
}

base::base(int a , int b)
: m_ia(a)
, m_ib(b)
, count()
{
}

And if you have a C++11 compiler that supports delegating constructors, you could create a 4 constructor that takes 3 arguments and have the other constructors delegate to that one.

base::base()
: base(0, 0, 0)
{
}

base::base(const int _count)
: base(0, 0, _count)
{
}

base::base(int a , int b)
: base(a, b, 0)
{
}

base::base(int a , int b, int count)
: m_ia(a)
, m_ib(b)
, count(count)
{
}

The last constructor can be made private if you don't want it to be part of the class interface.

3
votes

In c++11 you can have

protected:
    int m_ia , m_ib;
    const int count = 0;

It works in VS 2013.

0
votes

As per standard C++ and you current code you have to Initialize your const variable in constructor using initialize list so code can be modified as below :

#include"iostream"

using namespace std;

class base
{
public:
    base();
    base(const int _count);
    base(int a ,int b, const int _count);
    ~base();
protected:
    int m_ia , m_ib;
    const int count;
};
base::base():count(0)
{
}

base::base(const int _count):count(_count)
{
}

base::base(int a , int b, const int _count):count(0)
{
    m_ia = a; 
    m_ib = b;
}

base::~base()
{

}
int  main()
{
    base *obj2 = new base(1000);
    getchar();
    return 0;
}