Way to prevent calling default constructor of Base class?
Aug 7, 2010 at 3:40am UTC
Hi!
I have a Base class with a default constructor (parameterized with default value) and a Derived class with the same. I'm wondering if there's a way to call the Derived constructor and explicitly
avoid calling the one for the Base first. Here's an example of the situation, with its output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
#include <fstream>
using namespace std;
class Base
{
public :
Base(ifstream* FILE = NULL)
{
cout << "Base constructor!" << endl;
}
};
class Derived: public Base
{
public :
Derived(ifstream* FILE = NULL)
{
cout << "Derived constructor!" << endl;
}
};
int main()
{
Derived X;
return 0;
}
Base constructor!
Derived constructor!
So, is there a way to prevent the Base ctor from being called first? Thanks in advance!
Aug 7, 2010 at 4:02am UTC
Sure! Make a dummy constructor and call that instead:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
#include <fstream>
using namespace std;
class Base
{
public :
Base(ifstream* FILE = NULL)
{
cout << "Base constructor!" << endl;
}
Base(int ,int ){}
};
class Derived: public Base
{
public :
Derived(ifstream* FILE = NULL):Base(0,0)
{
cout << "Derived constructor!" << endl;
}
};
int main()
{
Derived X;
return 0;
}
Aug 7, 2010 at 4:04am UTC
Oh! I had completely forgotten the ctor syntax with the colon--I knew there had to be a way! Thank you!
This is what I get for not doing any coding at all for almost seven years and then trying to take on a large project....grumble grumble.... ;-)
Topic archived. No new replies allowed.