Search code examples
c++oopc++11abstract-classinitializer-list

Abstract class init in the initialization list


I want to understand the following c++ concept. class_a is abstract class and as per abstract class concept we cannot create any instance of it. i have used the initlization list and abstract class as well but never used following concept. In the code ,the initlization list of class_b, class_a is initlized. I want to understand what is meaning of initlizing it in the initilization list.

 class_b::class_b(int val):nameA::class_a()

in fileA.cpp

namespace nameA
{
class class_a
{
    public:
        virtual ~class_a(){};
        virtual void process()=0;
};
}

in fileb.h file

namespace nameB
{
class class_b  : public nameA::class_a
{
    public:
    class_b(int val);
}
}

in fileb.cpp file

namespace nameB
{
class_b::class_b(int val)
:nameA::class_a() //Want to understand this line...
}

Solution

  • It would be more clear with a slightly richer example. Because if the abstract base class has neither attributes nor methods it is harder to see how it can be initialized.

    class NamedProcessor {
        std::string name;    // a private attribute
    public:
        NamedProcessor(const std::string &name) : name(name) {}
        virtual ~NamedProcessor() {}
    
        // a pure virtual method to make the class abstract
        virtual void process() = 0;
    
        std::string getName() {
            return name;
        }
    };
    
    class Doubler : public NamedProcessor {
        int value;           // a private attribute
    
    public:
        Doubler(int initial = 1) : NamedProcessor("Doubler") {
            reset(initial);
        }
    
        void reset(int initial) {
            value = initial;
        }
    
        int getValue() {
            return value;
        }
    
        // the concrete implementation
        void process() {
            value *= 2;
        }
    };
    
    int main() {
        // Compiler would croak witherror : variable type 'NamedProcessor' is an abstract class
        // NamedProcessor wrong("Ill formed");
    
        Doubler doubler;
        std::cout << doubler.getName() << "\n";     // name has been initialized...
        return 0;
    }
    

    Here the abstract class holds an attribute which will be available to subclasses. And this attribute has to be set at construction time because there is no public setter for it. The language has to provide a way to initialize the abstract subclass, meaning not building an object, but initializing a sub-object - here setting the name.