Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create the instance of a concrete implementation of a class in C++ as in Java?

Maybe it’s a little weird question, but: I’m not so much familiar with C++.

Let’s say we have an abstract class A and a class B that extends it:

abstract class A {
    abstract void foo();
}

class B extends A {
    @Override
    void foo() {
        // . . .
    }
}

Then, in the Test class, we can create an instance of B this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Test {
    A a = new B();
}

Can I do something like this in C++?

Because, when I do the same in C++, I receive something like this:
error

(I have an abstract class Customer that’s being extended by other class. There’s being performed smth like this Customer* customer = new OnlineCustomer();)

>Solution :

In C++ you can’t construct an abstract class, but you can make a pointer to an abstract class. Here’s a direct translation of your code to C++:

#include <iostream>

struct A // structs are classes that are default public
{
    // having at least one method be
    // "= 0" flags the class as abstract:
    virtual void foo() = 0;
    virtual ~A() = default;
};

struct B : A
{
    void foo() override
    {
        std::cout << "Hello World" << std::endl;
    }
};

int main()
{
    // Test:
    // (in C++ not everything is about classes!)

    // Where 'a' OWNS the data:
    A* a1 = new B;
    a1->foo();
    delete a1;

    // Where 'a' REFERS to the data:
    B b;
    A* a2 = &b;
    a2->foo();
}

demo

Note that where Java is all about OOP and inheritance, in C++ OOP is just one of the tools in the tool box, and inheritance – although it has its place – is often seen as causing more problems than it solves (often templates or functional programming or composition would do better).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading