Why am I able to dereference a pointer to an abstract class?

Viewed 1076

In the code below, IContainer is a pure abstract class: it does not contain any methods which are not pure virtual. This being the case, I don't expect to be able to instantiate an object of type IContainer, however I do expect to be able to hold an instance of a derived class in an IContainer*.

In main below, I have created some instances of the concrete class SimpleContainer which implements IContainer. Next, I have stored a pointer to these SimpleContainers in some IContainer* variables.

Here is my question: since IContainer is an abstract class, I cannot instantiate it. However, at the bottom of my main you can see that I dereference my IContainer pointers in order to check equality. Why am I able to do this? Also, is there any difference between iCont1 == iCont2 and *iCont1 == *iCont2?

#include <iostream>

class IContainer{
    public:
        virtual bool operator==(const IContainer& aICont) const = 0;
        virtual int getVal() const = 0;
};

class SimpleContainer : public IContainer{
    public:
        SimpleContainer(int val) : val(val){};
        int getVal() const override {return val;}
        bool operator==(const IContainer& aICont) const override
        {
            return val == aICont.getVal();
        }
    private:
        int val;
};

int main(){
    SimpleContainer cont1(1), cont2(2), cont3(1);
    IContainer* iCont1 = &cont1;
    IContainer* iCont2 = &cont2;
    IContainer* iCont3 = &cont3;

    std::cout << "iCont1 == iCont2 -> " << (iCont1 == iCont2 ? "true" : "false") << " || Expecting -> " << "false" << std::endl;        
    std::cout << "*iCont1 == *iCont2 -> " << (*iCont1 == *iCont2 ? "true" : "false") << " || Expecting -> " << "false" << std::endl; 
    std::cout << "iCont1 == iCont3 -> " << (iCont1 == iCont3 ? "true" : "false") << " || Expecting -> " << "false" << std::endl; 
    std::cout << "*iCont1 == *iCont3 -> " << (*iCont1 == *iCont3 ? "true" : "false") << " || Expecting -> " << "false" << std::endl; 
    return 0;
}  
2 Answers
Related