S
S
Sergey Ivchenko2015-10-23 08:20:39
C++ / C#
Sergey Ivchenko, 2015-10-23 08:20:39

How to create an instance of a class that implements an interface?

I create an abstract class:

class iClass {
public:
void method1();
virtual method2();
}

class myClass : public iClass {
/*тут методы родителя*/
void method3();
}

How to create an instance of the myClass class through the iClass interface and use method3() on this instance?
QtCreator says to do this :
iClass c = new myClass();
but after that the c object has no method3() method.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Ivchenko, 2015-10-23
@Serg89

The issue was resolved by typecasting:
myClass c = (myClass * ) new iClass();

S
Stanislav Makarov, 2015-10-23
@Nipheris

The tin is full.

class iClass {
public:
void method1();
virtual method2();
}

This is not an abstract class, an abstract one must have underdefined behavior, i.e. at least one pure-virtual method. You have a virtual method, but it is expected to be released. If iClass were abstract, then the code
would not compile in any way
That's right - no way, the task is set incorrectly. If you have some interface, you need to work through it. If you need to create instances of different implementation classes, you must write new ConcreteClass() and then optionally cast to an interface type. If you need method3 then you DO NOT NEED iClass, you need myClass because It is IN IT that there is a method3.
If you have the task of creating an instance of a specific (non-abstract) class depending on some parameters, read about factories. But first, get over the basics, you don't understand what you're doing yet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question