How to initialize an object of derived class when the derived class and base class both have parameterized constructors?
I am facing problem in initializing objects. Following is a piece of code,
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
Base(int a)
{
m_a = a;
}
private:
int m_a;
};
class Derived:public Base
{
public:
Derived(char a)
{
m_a = a;
}
private:
char m_a;开发者_开发知识库
};
void main()
{
_getch();
}
Compiling the above code gives the following error, error C2512: 'Base' : no appropriate default constructor available
I know that since derived class and base class both have only parametrized constructors i need to initialize the base class object in derived class constructor. But i don't know how to do it. Can anyone please tell me as to what is wrong in the above code?
public:
Derived(char a):Base(/*int Parameter*/),m_a(a)
{
}
After making trails i one more way to initialize the base class too, Following is the code,
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
Base(int a)
{
m_a = a;
}
private:
int m_a;
};
class Derived:public Base
{
public:
Derived(int b, char a):Base(b)
{
m_a = a;
}
private:
char m_a;
};
void main()
{
Derived d(10,'A');
_getch();
}
精彩评论