Thursday, December 27, 2012

Can I declare a constructor for an abstract class?

This may sound odd, but an abstract class may have constructors, but they cannot be used to instantiate
the abstract class. If you write statements to call the constructor the compiler will fail and report the
class is "abstract; cannot be instantiated".

#include <iostream>
using namespace std;
class BaseClass {
public:
    BaseClass(){
    }
    BaseClass(int i){
    }
    virtual void paint() = 0;
    virtual void draw() = 0;
};
int main()
{
    return 0;
}


Constructors in abstract classes are designed only to be used by their subclasses using a super() call in
their own constructors. Though the abstract class cannot stand as an instance in its own right, when its
abstract methods are fulfilled by a subclass, its constructors can be called upon to deliver stock
template-like initialisation behaviour, for example.

#include <iostream>
using namespace std;
class BaseClass {
public:
    BaseClass(){
    }
    BaseClass(int i){
    }
    virtual void paint() = 0;
    virtual void draw() = 0;
};
class DerivedClass: public BaseClass {
    int j;
public:
    DerivedClass(int x, int y): BaseClass(y) {
        j = x;
        cout << "Constructing DerivedClass\n";
    }
    ~DerivedClass() {
        cout << "Destructing DerivedClass\n";
}
    virtual void draw(){
    }
    virtual void paint(){
    }
};
int main()
{
    DerivedClass dc(2,3);
    return 0;
}

No comments:

Post a Comment