I have already seen a post about the error but This is some what different. So please donot close this. I have an Interface class and I have a class that inherits the interface class and overides the methods in Interface class. The code looks likes this
//interface file
//Interface.h
class A
{
virtual method1();
};
//b.h
#include "Interface.h"
class B : public A
{
//declaration
}
//b.cxx
#include b.h
B::method1()
{
//definition
}
I am exporting all these classes in a dll. And I am using methods and classes in the dll from an exe. This exe agains contains somes classes. These classes again inherit the same interface file and also uses method1(). So to use method1() I am including b.h in my file. If order of my include statements are Interface.h and b.h, then I am getting Compiler error for exe. Telling "base class not defined". But if I reorder the Include statement there is no compilation error. Can any one suggest me what could be basic reason for this problem.
There are actually two errors in your example code: First you do not declare the method without a return type, which is an error. The second is that you, at least in the snippet above, do not declare method1 in the class definition of B:
class B : public A
{
virtual void method1();
};
You absolutely need to declare virtual method "method1()" in both A and B's class definition.
If you interface is IA and is declared in IA.h , make sure that every class Foo that inherits from IA be it in the exe or dll includes IA.h before the class definition in Foo.h
What I suspect is happening that this is not the case and based on the header include order you might be getting the definition of IA in certain files and not in the others
Related
I'm working on a simple C++ program and am having a difficult time understanding a compiler error I was getting. The issue was caused by me attempting to create a derived class from a base class. I've posted my code below with the same structure but have changed the names.
BaseClass.h
#ifndef BASECLASS_H
#define BASECLASS_H
class BaseClass {
public:
BaseClass(void);
virtual int method1(void) = 0;
virtual int method2(void) = 0;
virtual float method3(void) = 0;
};
#endif // BASECLASS_H
DerivedClass.h
#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H
#include "DerivedClass.h"
class DerivedClass: public BaseClass
{
public:
DerivedClass(void);
};
#endif // DERIVEDCLASS_H
DerivedClass.cpp
#include "DerivedClass.h"
DerivedClass::DerivedClass(void)
{
}
int DerivedClass::method1(void)
{
// TODO
}
int DerivedClass::method2(void)
{
// TODO
}
float DerivedClass::method3(void)
{
// TODO
}
When attempting to compile this, I get the following error for all the virtual methods:
no 'int DerivedClass::methodX()' member function declared in class 'DerivedClass'
As soon as I declare these methods in the 'DerivedClass.h', the errors go away since the compiler is now aware of the methods.
However, I'm confused. Why was it necessary to re-declare the pure virtual functions in DerivedClass.h? When I #include DerivedClass.h, that will automatically include BaseClass.h, thus I assume my DerivedClass.cpp should be fully aware of the methods. Am I doing something incorrect?
It doesn't work this way. You need to declare the methods you're going to define, whether they're overriding a virtual method or not.
This isn't just an unreasonable requirement of the language. Without this you would be unable to define partially virtual class, i.e., you could have BaseSubtype that has common implementation of method1() but requires classes derived from it to implement method2() and method3()
When you declare a method in a derived class, you say to the compiler:
I want to override this method in this class
So if you don't declare a method in the derived class, you say:
I don't want to override this method; derived class's implementation is the same as the one in the base class
In your case, the base class declares them as pure virtual, so in this case it can be paraphrased:
I don't want to implement this method in this class
If you try to define a method but not declare it, you contradict yourself. The compiler detects that (to protect you from your own negligence).
A very non-intuitive reason why overridden virtual methods must be derived in the base class stems from the fact that C++ allows different parts of the class to be placed into different files, into different translation units.
With some other languages (I'm looking in Java's direction), a single class must be placed in a single file. This is not true with C++. It is perfectly legal for a class to have some of its methods declared in one translation unit, and other methods declared in another translation unit, which could be in a file in some different directory altogether.
Each such file gets compiled separately and individually. When compiling one translation, the C++ compiler has no knowledge of any other translation unit, any other file, that might contain other pieces of the same class.
Now let's say that you are allowed to omit an overriden virtual method from the class declaration. This creates an immediate problem: when compiling the class's constructor, it is necessary for the compiler to know whether the class overrides any virtual methods from any of the superclasses, in order to correctly assemble the virtual table dispatch for the class being constructed. Without an explicit declaration, the compiler has no way of knowing whether or not some other translation unit might define an overridden virtual method.
And that's why overridden virtual methods must be explicitly included in the class's declaration. In conclusion: because C++ formally specifies phase 9, the linkage phase, with the actual compilation carried on in earlier phases, overridden methods must be explicitly declared.
you should override all the base class pure virtual functions to be able to instantiate derived class.
you cannot define a base class member function from derived class.
in your example you are trying to define method1 and method2 and method3 which are not members of DerivedClass!! you have to declare them yourself in your derived class. compiler doesn't do it for you.
so your Derivedclass.h will look like:
#ifndef DERIVEDCLASS_H
#define DERIVEDCLASS_H
#include "BaseClass.h"
class DerivedClass: public BaseClass
{
public:
DerivedClass(void);
virtual int method1(void); // not pure function
virtual int method2(void);
virtual float method3(void);
};
#endif // DERIVEDCLASS_H
I have a library which I'm porting to Windows/MSVC. The library is C++, and uses the following pattern to hide the implementation. I'm trying to use the suggested way to export the entire class with dllexport on the class declaration.
#define API __declspec(dllexport)
class API Something
{
public:
static Something * instantiate();
void doSomething() = 0;
// etc
};
Then there is a private implementation which implements the static factory method and all the other methods.
// SomethingImpl.h
class SomethingImpl : public Something
{
//... normal overrides
}
// SomethingImpl.cpp
Something * SomethingImpl::instantiate()
{
return new SomethingImpl();
}
void SomethingImpl::doSomething()
{
// something great
}
However when I think link the DLL to my application, all these symbols are not found by the linker (LNK2019). I suppose that because they are pure virtual methods it assumes they are not needed? Any hints?
The other more normal classes are linking OK, and when I see the DLL in dependency walker, the symbols are definitely not there for these classes.
Thanks
Your assumption is correct in the sense, that the base class (Something) is not exported. More specifically, there is no actual code generated for the base class (since it is a pure virtual class). Hence there are no symbols that could be exported.
On the derived class (SomethingImpl) however you have to dllexport the private implementation for the consumer of the dll. The dllexport of the base class is not inherited by the derived class. But you have to export these symbols in order of allowing a consumer actually using this code. That does not mean your implementation details become "public" to the consumer.
As an example, imagine a consumer of your dll declares a class with a member of type Something. When this class calls Something::instantiate(), the linker needs to know which actual address needs to be called. Hence your implementation must be exported.
I'm new to programming in c++ and struggle with organizing my project.
I have got a class named StateManager, which has a header file and an cpp file.
The cpp contains all implementations.
If I now want to make an Interface class:
class IStateManager
{
public:
virtual ~IStateManager() {}
virtual void SomeMethod {}
};
I know interfaces don't really exist as they do in c# or Java, but I want multiple classes to inherit from this "interface".
Does this class also need an header and a cpp file? Or can I just put it in a header file?
Technically, c++ doesn't have interfaces. However, one can "create" interfaces by way of multiple inheritance (or single inheritance if your class is a "base" class and doesn't need to inherit from multiple classes). Where your "interface" lives is entirely up to you. But if you plan on using a class as an interface (without any actual implementation because technically an interface doesn't have an implementation until the functions are defined in a subclass), I would put it in it's own header file and declare each function pure virtual:
class IStateManager
{
public:
virtual ~IStateManager() {}
virtual void SomeMethod() = 0;
virtual void AnotherMethod() = 0;
};
class TheState : public IStateManager, public SomeOtherParentClass
{
virtual void SomeMethod(); // Defined in this class
virtual void AnotherMethod(); // Also defined in this class
//..
};
If you are defining some implementation in a .cpp for the IStateManager class, then you really have more of an abstract class and not an interface.
So in conclusion what I'm saying is: Any implementation of an "interface" should be defined in the .cpp file of its implementing class. And if you plan on using the interface in multiple files, I would create a separate .h file for it.
You can put the implementation of class methods in the header file. That doesn't mean you should. It also has nothing to do with the fact that this is an "interface" class, as you call it.
I wouldn't call this an interface class by the way, because your virtual methods aren't pure.
I have a C++ program A.cpp and I'm including two header files X.h and Y.h. This program(A.cpp) has a class 'foo' and the prototypes of all members of that class. The implementation of this class is done in X.h and Y.h. Both of them contain different definitions of the member functions. But the inclusion of one these files is done conditionally using #ifdef in the program. So if a certain condition is satisified, X.h is #include-ed, else Y.h is #include-ed. Both of them are never included together. Here's the problem: I need to change this compile-time toggle to run-time toggle. I know a header file cannot be included during run-time, so is there any way in which I can "choose" which implementation I want, without using namespaces? Overloading is ruled out, because the functions' prototypes are the same.
Thanks a lot.
(Sorry if this is stupid. I a newbie in C++)
If you want two different behaviours at runtime, then it sounds like you're describing polymorphism. Consider writing two different classes that inherit from a common base-class with virtual functions. Then at runtime you can do things like this:
Animal &a = (x == 3) ? Dog() : Cat();
a.talk();
Perhaps you want to consider a static factory method pattern? You can have a single method which returns the instance of your choice to the caller. You would need to subclass as OliCharlesworth suggests, then this would make it transparent to the calling code.
In pseudocode.
class baseclass{
...
static baseclass *GimmeImpl(){
if(aImpl){
return A();
}else{
return B();
}
}
};
class A:public baseclass {...};
class B:public baseclass {...};
I am new at building distributable libraries written in C++ and I am getting a bit lost.
I have created a .cpp file with wrappers for all functions I want the library to offer users, and I have written 2 .h files, one public and one private. Below is a dummy example of my header files:
public.h:
class myclass
{
public:
public_function();
private:
}
private.h:
class myclass
{
public:
public_function();
private:
anotherClass instanceofClass;
}
Note that the implementation of public_function() uses the "instanceofClass" in the code.
I have been able to compile with no problem the code using the private class and to compile and link the library with external programs using the public header and the compiled library. When executing that code, though, I am getting segmentation faults that I suspect have to do with lack of proper initialization of "instanceofClass".
Am I doing the right thing? Am I forced to instantiate "instanceofClass" inside the implementation of public_function() for it to be initialized properly, or is there anything else I should do instead?
Thanks a lot.
You can't declare the same class 'myclass' in two different ways. There has to be a single class definition. If you want to hide the implementation's API you want to use the 'Pimpl' idiom. So your public class has a single pointer to a private class. For example:
public.h
class myclass_private;
class myclass {
private:
myclass_private* pimpl;
public:
myclass();
void public_function();
};
public.cpp
myclass::myclass() {
pimpl = new myclass_private;
}
void myclass::public_function() {
pimpl->private_function();
}
private.h
class myclass_private {
public:
void private_function();
};
The myclass defined in public.h has no members, and is therefore sized 1 byte. The myclass defined in private.h encapsulates anotherClass, and is therefore whatever size anotherClass is. This inconsistency is the root of your problem.
What you ought to do is have only one header, and use a pointer (which doesn't require a class definition) to enable hiding the implementation of anotherClass. I'll repeat Joachim's link to the pimpl idiom for elaboration.
The definition of a class shall not changr between different translation units. This is one of the aspects of the One Definition Rule. What you might want to donis to define the publicly visible class to have a pointer to a private implementation: the Pimpl Idiom:
class Public {
public:
...
private:
struct Impl;
Impl* impl_;
};
The struct Impl would only be defined in the implementation file.
Your class lacks a proper constructor, which means that the compiler will provide a default one based on the content of the class definition. If that definition isn't consistent accross all the code, it won't get initialized the same way everywhere, and some data may be missing.
If you want to hide the implementation details of instanceofClass, just do a forward declaration in the header (the private header you're providing is correct, you can use it as your public one), and provide an implementation somewhere in your code.