Base method gets called instead of derived method - c++

I am currently trying to deliver more than one implementation of an header file. I tried doing this like this:
// A.h:
class A {
public:
A();
~A();
bool method1();
bool method2();
}
// A.cpp:
A::A() {
}
A::~A() {
}
bool A::method1() {
}
bool A::method2() {
}
// B.h
class B : public A {
public B();
public ~B();
bool method1();
bool method2();
}
// B.cpp
B::B() {
}
B::~B() {
}
bool B::method1() {
// actual code I want to use
}
bool B::method2() {
// actual code I want to use
}
// AFactory.h
#define USE_B 10
#define USE_C 20
#define IMPL USE_B
class A;
class AFactory {
public:
static A *getImplementation();
}
// AFactory.cpp
A *AFactory::getImplementation() {
#if IMPL == USE_B
return new B();
#elif IMPL == USE_C
return new C();
#else
return NULL;
#endif
}
// Test.cpp
int main () {
A *test = AFactory::getImplementation();
test->method1();
test->method2();
}
The idea was, to deliver more than one implementation of the class A, which could be switched by simply changing the value of the define IMPL. The problem is, that the methods from the actual used implementation B are never called. The methods from the base class A are called instead. I tried to remove the A.cpp completly from the build, since it's never used or rather should never be used, but then it won't build, telling me, that I have undefined references in my test code.

If you want to override these methods, you use the virtual keyword.
class A
{
virtual bool method1();
}
class B : public A
{
virtual bool method1(); // If you want to override the base functionality.
}

Related

Avoiding repetitive sub-class definitions in C++

I am new to C++ classes, and I have a question about defining multiple sub-classes of an abstract type/interface which would have identical definitions.
Take the following example which might appear in a header file with 3 sub-classes:
class Animal {
private:
int a;
int b;
public:
explicit Animal(int a) {}
virtual Animal* getFriend() = 0;
virtual bool walk() = 0;
virtual bool talk() = 0;
virtual bool someFunction() = 0;
virtual bool someOtherFunction() = 0;
// ... many more functions
}
class Zebra: public Animal {
Animal* getFriend();
bool walk();
bool someFunction();
bool someOtherFunction();
// ... continues for many more functions
}
class Cow: public Animal {
Animal* getFriend();
bool walk();
bool someFunction();
bool someOtherFunction();
// ... continues for many more functions
}
class Salmon: public Animal {
Animal* getFriend();
bool walk();
bool someFunction();
bool someOtherFunction();
// ... continues for many more functions
}
// ... many more animals
Declaring the sub-classes like this seems repetitive and potentially error prone. Because the class definitions are identical except for the name of the class, is there a more efficient way to declare the animal sub-classes in bulk?
In the context I am working in each animal would have a completely independent implementation in separate .cpp files.
Please let me know if i'm approaching this completely wrong. Any help would be greatly appreciated.
It is indeed error prone when you don't make use of the override keyword for each overridden virtual class member function.
Instead of declaring the derived class function like this
bool someFunction();
you can/should declare it like this
bool someFunction() override;
In this way, you would get a compilation error if the declaration doesn't match the base class signature. Without it, you would have a perfectly good compilable program but with a behaviour bug.
Other than that, your strategy is fine, and is the way to do handle abstract functions.
I'm writing another answer as an alternative solution. Actually, If i faced with same 'issue' or 'problem', i would not declare as bulk, I would just create zebra.h, zebra.cpp, inherits from Animal and declare/define all members individually. In other words i would prefer not to be clever but if you want to be the piece of codes below could be an alternative.
Indeed, you just want to create a class declaration from a template. That's what template is doing. It is possible to mimic same behaviour with MACROs but I would prefer template rather than MACRO because it is what Bjarne did.
So here is the code
animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal {
private:
int a;
int b;
public:
explicit Animal(int a) {}
virtual ~Animal() = default; // You should this virtual destructor
// for polymorphic types.
virtual Animal* getFriend() = 0;
virtual bool walk() = 0;
virtual bool talk() = 0;
virtual bool someFunction() = 0;
virtual bool someOtherFunction() = 0;
};
enum class animal_types
{
zebra ,
cow ,
salmon ,
special_animal
};
template< animal_types >
struct ugly_bulk_animal_inheritor : Animal
{
using Animal::Animal; // Use parent constructor as is
Animal* getFriend() override;
bool walk() override;
bool talk() override;
bool someFunction() override;
bool someOtherFunction() override;
};
using Zebra = ugly_bulk_animal_inheritor< animal_types::zebra >;
using Cow = ugly_bulk_animal_inheritor< animal_types::cow >;
using Salmon = ugly_bulk_animal_inheritor< animal_types::salmon >;
// So on..
#include "zebra.h"
#include "salmon.h"
#include "cow.h"
#include "special_animal.h"
#endif // ANIMAL_H
cow.h
#ifndef COW_H
#define COW_H
#include "animal.h"
template<>
Animal* Cow::getFriend() {
return nullptr;
}
template<>
bool Cow::walk() {
return true;
}
template<>
bool Cow::talk() {
return false;
}
template<>
bool Cow::someFunction() {
return true;
}
template<>
bool Cow::someOtherFunction() {
return true;
}
#endif // COW_H
salmon.h
#ifndef SALMON_H
#define SALMON_H
#include "animal.h"
template<>
Animal* Salmon::getFriend() {
return nullptr;
}
template<>
bool Salmon::walk() {
return true;
}
template<>
bool Salmon::talk() {
return true;
}
template<>
bool Salmon::someFunction() {
return true;
}
template<>
bool Salmon::someOtherFunction() {
return true;
}
#endif // SALMON_H
zebra.h
#ifndef ZEBRA_H
#define ZEBRA_H
#include "animal.h"
template<>
Animal* Zebra::getFriend() {
return nullptr;
}
template<>
bool Zebra::walk() {
return true;
}
template<>
bool Zebra::talk() {
return false;
}
template<>
bool Zebra::someFunction() {
return true;
}
template<>
bool Zebra::someOtherFunction() {
return true;
}
#endif // ZEBRA_H
special_animal.h
#ifndef SPECIAL_ANIMAL_H
#define SPECIAL_ANIMAL_H
#include "animal.h"
#include <iostream>
template<>
struct ugly_bulk_animal_inheritor<animal_types::special_animal> : Animal
{
using Animal::Animal; // Use parent constructor as is
Animal* getFriend() override { return nullptr; }
bool walk() override { return true; }
bool talk() override { return true; }
bool someFunction() override { return true; }
bool someOtherFunction() override { return true; }
void specility_fn() {
std::cout << "A speciality" << std::endl;
}
private:
int some_extra_member;
// etc..
};
using special_animal = ugly_bulk_animal_inheritor<animal_types::special_animal>;
#endif // SPECIAL_ANIMAL_H
main.cpp
#include <iostream>
#include "animal.h"
int main(int argc, char *argv[])
{
Animal* instance;
Zebra z { 5 };
Cow c { 6 };
Salmon t { 7 };
instance = &z;
std::cout << "Zebra can talk ? " << instance->talk() << std::endl;
instance = &t;
std::cout << "Salmon can talk ? " << instance->talk() << std::endl;
special_animal s { 5 };
s.specility_fn();
return 0;
}
Short of using a macro to define the classes (which is even worse!), there probably isn't a great deal you can do. Occasionally stuff like this might work, but I'd wager that at some point, you'd want to specialise one of the animals, leading to you ditching the macro again. It's for that reason I'd avoid that particular technique.
#define DECLARE_ANIMAL(ANIMAL_TYPE) \
class ANIMAL_TYPE: public Animal { \
Animal* getFriend() override; \
bool walk() override; \
bool someFunction() override; \
bool someOtherFunction() override; \
};
DECLARE_ANIMAL(Zebra);
DECLARE_ANIMAL(Cow);
DECLARE_ANIMAL(Salmon);
Generally speaking, try to move as much of the duplicated class methods & data into the base class to minimise the amount of code duplication. This may require a slight change in the way you think about the problem though....
For example, walk(). In the case of a Cow/Zebra/Horse/Cat/Dog, the act of walking is pretty much identical. The only real differences can be measured with data (e.g. the walk speed, how many legs are used, what is the gait of the walk, how large is each stride?). If you can define the behaviour in a data-driven fashion, you would just need to set those parameters in the Derived class constructor, and avoid the need for
customised methods. Approaching the class design this way has a few other benefits, for example you'd have a single 'Dog' class, but it would be able to represent a 4 legged dog, and a 3 legged dog, without needing to create a new class.
That's usually the approach I'd recommend anyway...

Requiring derived class to define a method

I am no doubt overlooking something basic but my implementation is obviously flawed.
I am trying to require a derived classes to implement a method being called in a base class.
class IClock
{
public:
virtual void OnTimeExpired() = 0;
}
class Clock : public IClock
{
... // ABC not implemented
}
class Application : public Clock
{
... // ABC not implemented
}
class DerivedApp : public Application
{
public:
virtual void OnTimeExpired() { ... }
}
I rarely use pure ABCs, so I thought by not defining the pure virtual method in Clock and Application, it would require all derivatives of Application to define the OnTimeExpired() method.
I discovered this will compile and link (MSVS-2017) and if DerivedApp does not implement the method, the Clock object will call an undefined method and crash.
Why does this compile without the pure virtual method being implemented?
How do I force derived Application classes to implement the OnTimeExpired() method?
EDIT: The crash was due to unrelated error - I apologize. Nevertheless the questions I ask are still applicable.
As requested here is a complete, buildable, minimal example:
IClock.h:
#pragma once
class IClock
{
public:
virtual void OnClockTime() = 0;
};
Clock.h:
#pragma once
#include "IClock.h"
class Clock : public IClock
{
public:
Clock();
virtual ~Clock();
void ClockUpdate();
virtual void OnClockTime();
private:
float elapsed_time;
};
Clock.cpp:
#include "Clock.h"
Clock::Clock()
: elapsed_time(0.0f)
{
}
Clock::~Clock()
{
}
void Clock::ClockUpdate()
{
elapsed_time += 0.0000001f; // small ticks for testing
if (elapsed_time >= 1.0f) {
OnClockTime();
elapsed_time -= 1.0f;
}
}
void Clock::OnClockTime()
{}
ApplicationBase.h
#pragma once
#include "Clock.h"
class ApplicationBase : public Clock
{
public:
ApplicationBase();
virtual ~ApplicationBase();
virtual void Init(){}
virtual void Run(){}
protected:
bool app_run;
};
ApplicationBase.cpp:
#include "ApplicationBase.h"
ApplicationBase::ApplicationBase()
: app_run(false)
{
}
ApplicationBase::~ApplicationBase()
{
}
DerivedApp.h:
#pragma once
#include "ApplicationBase.h"
class DerivedApp : public ApplicationBase
{
public:
DerivedApp();
virtual ~DerivedApp();
virtual void Init() {}
virtual void Run();
//virtual void OnClockTime();
};
DerivedApp.cpp:
#include "DerivedApp.h"
#include <iostream>
DerivedApp::DerivedApp()
{
}
DerivedApp::~DerivedApp()
{
}
void DerivedApp::Run()
{
app_run = true;
while (app_run) {
ClockUpdate();
}
}
//void DerivedApp::OnClockTime()
//{
// static int counts(0);
// std::cout << "Tick..." << std::endl;
// counts++;
// if (counts >= 10)
// app_run = false;
//}
main.cpp
#include "DerivedApp.h"
class App : public DerivedApp
{
public:
App(){}
~App(){}
};
int wmain(int argc, wchar_t * argv[])
{
App *app = new App();
app->Init();
app->Run();
delete app;
}
Thanks to those who requested a minimal working example, I built it and it works exactly as I had hoped. The complier will complain about no instantiation of the ABC in the App class. If I remove the comments from DerivedApp::OnClockTime() it compiles and runs the way I wish. Obviously my actual code is not following this model as I thought, so now I need to reexamine where I went wrong. Thanks.
There is no keyword in C++ that forces a class to override some method. However, by making OnTimeExpired() pure virtual you're making IClock an abstract class. Any classes deriving from IClock that do not implement OnTimeExpired() will automatically become an abstract class too, thus not allowing you to create objects of these classes. This means that your code as-is is completely legal unless you try to make objects of these classes
class AbstractBase {
public:
virtual void someFunc() = 0; // Purely Virtual
};
class AbstractDerived : public AbstractBase {
public:
void someOtherFunc();
// Still abstract because the following is not declared-defined
// void someFunc() override { ... }
};
class NonAbstractDerivedA : public AbstractBase { // Derived From Base
public:
void someFunc() override { /* do this class's implementation*/ }
};
class NonAbstractDerivedB : public AbstractDerived { // Derived From AbstractDerived
public:
void someFunc() override { /* do this class's implementation*/ }
};
uses:
#include "above"
int main() {
AbstractBase base; // compiler error
AbstractDerived derived; // compiler error
NonAbstractDerivedA derivedA; // should be okay
NonAbstractDerivedB derivedB; // should be okay
return 0;
}

Call a method from A class in constructor of other class

I want to call a method from A class in constructor of other class
I googled, but did not find any answer
For example, I have :
class A{
void doWork();
}
class B{
B(){
//here i want to have doWork method
}
}
You told us not enough to choose proper solution. Everything depends on what you are trying to achieve. A few solutions:
a) Mark A method as static.
class A
{
public:
static void DoSth()
{
// Cannot access non-static A members here!
}
};
class B
{
public:
B()
{
A::DoSth();
}
};
b) You can instantiate A in place
class A
{
public:
void DoSth()
{
// Do something
}
};
class B
{
public:
B()
{
A a;
a.DoSth();
}
};
c) You can put A's instance into B:
// A remains as in b)
class B
{
private:
A a;
// or: A * a;
public:
B()
{
a.DoSth();
// or: a = new A; a->DoSth();
// Remember to free a somewhere
// (probably in destructor)
}
}
d) You may derive B from A:
class A
{
protected:
void DoSth()
{
}
};
class B : public A
{
public:
B()
{
DoSth();
}
};
e) You can forget about A class and make DoSth a function:
void DoSth()
{
// ...
}
class B
{
public:
B()
{
DoSth();
}
}
Since you provided not enough data, you have to choose solution on your own.
In order for that to work you'd need to subclass it.
So it'd be like this:
class A {
doWork();
}
class B : A {
B(){
doWork();
}
}
You could also do it like so going for a HAS-A rather than IS-A relationship:
class A {
doWork();
}
class B {
A myA;
B(){
myA.doWork();
}
}
Without knowing more of what you are doing I'd go with the top (IS-A) solution which is what I think you are trying to do.
Or
class A
{
public:
static void doWork();
};
class B
{
B(void)
{
A::doWork();
}
};
?
PS: Here B::B() will be private

C++ Have One Nested Class Inherit From Another Nested Class

I'm writing a cross-platform class hierarchy, and want to keep the platform dependent implementations in their own class (as opposed to having one class with #ifdefs). This is what I have so far, but the compiler is complaining that BaseDef is private. Any help with how I could keep this basic structure while getting it to compile would be greatly appreciated :-)
Edit: It would seem from here that this isn't possible. Any other way I could keep this general structure and still compile?
Root.h
class Root {
private:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
#ifdef _WIN32
class WinImp;
#else
class NixImp;
#endif
BaseDef* imp;
BaseDef* getImp();
public:
Root() : imp(getImp()) {}
void foo();
void bar();
};
Root.cpp
#include "Root.h"
void Root::foo() {
imp->foo();
}
void Root::bar() {
imp->bar();
}
WinImp.h
#ifdef _WIN32
#include "Root.h"
class WinImp : public Root::BaseDef {
public:
void foo();
void bar();
};
#endif
WinImp.cpp
#include "WinImp.h"
#ifdef _WIN32
Root::WinImp::foo() {
}
Root::WinImp::bar() {
}
Root::BaseDef* Root::getImp() {
return new Root::WinImp();
}
#endif
Your main problem is that BaseDef is private. That means that other classes (aside from Root itself) cannot access the BaseDef name. One way is to make BaseDef public. Alternatively you can make the derived classes (WinImp and NixImp) friends of Root so that they can access the BaseDef name. In addition Root cannot access the members of BaseDef so they need to be public or make Root a friend of BaseDef.
class Root {
private:
class BaseDef {
public:
// These need to be public so that Root can see them or Root needs to be a friend.
//Nothing else can see BaseDef though so this is safe.
virtual void foo() = 0;
virtual void bar() = 0;
};
class WinImp; // Forward declare the classes
friend class WinImp; // And then make them friends
class NixImp;
friend class NixImp;
BaseDef* imp;
BaseDef* getImp();
public:
Root() : imp(getImp()) {}
void foo();
void bar();
};
void Root::foo() {
imp->foo();
}
void Root::bar() {
imp->bar();
}
// Since this is a nested class i made it Root::WinImp
class Root::WinImp : public Root::BaseDef {
public:
void foo();
void bar();
};
void Root::WinImp::foo() {}
void Root::WinImp::bar() {}
Root::BaseDef* Root::getImp() {
return new WinImp();
}
This method is not allowed according to the 2003 standard (11.4.p2) but in C++11 (same example) it is explicitly allowed (11.3.p2). However, clang (3.1 tested) accepts this even in 2003 mode. gcc (4.7.2 tested) accepts this (even in 2003 mode) so long as the derived classes are nested inside the same class but not if outside the class.
It's complaining that BaseDef is private...
class Root {
private:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
So make it public...
class Root {
public:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
Footnote:
You're trying to avoid #ifdef, so get rid of this:
#ifdef _WIN32
class WinImp;
#else
class NixImp;
#endif
Instead, just use a single class:
class Imp;

Solving cross referencing

I have a problem creating some form of hierarchy with different object types. I have a class which has a member of another class, like this:
class A
{
public:
A(){}
~A(){}
void addB(B* dep){
child = dep;
dep->addOwner(this);
}
void updateChild(){
child->printOwner();
}
void print(){
printf("Printing...");
}
private:
B* child;
};
And this is class B:
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
Calling a function of "B" out of class "A" works just fine but trying it vice versa gives a compiler error because A is not defined in B. It actually is by using an include and a forward declaration, but I guess its a cross reference problem which the compiler can not solve.
Is there any chance to solve this problem or should I rethink my design?
You say that you already solved your circular dependency problem by using a forward declaration of A instead of including the header where A is defined, so you already know how to avoid circular includes. However, you should be aware of what is possible and what is not with incomplete types (i.e. types that have been forward declared).
In your case, you try to call the member function print on an object that has an incomplete type; the compiler knows nothing about this type excepts that it will be defined at some point, so it does not allow you to do this. The solution is to remove the implementation of the printOwner member function from the B header and put it into an implementation file:
//B.hpp
class A; // forward declaration
class B
{
public:
void addOwner(A* owner);
void printOwner() const; // I think this member function could be const
private:
A* ownerObject;
};
//B.cpp
#include "B.hpp"
#include "A.hpp" // here we "import" the definition of A
void B::addOwner(A * owner)
{
ownerObject = owner;
}
void B::printOwner() const
{
ownerObject->print(); //A is complete now, so we can use its member functions
}
You could possibly do the same thing in the A header.
You can use forward declaration, and define the member functions outside of the class, i.e.
// A.h
class B;
class A { public:
void addB(B* dep); // don't define addB here.
...
};
// B.h
class A;
class B { public:
void addOwner(A* owner); // don't define addOwner here.
...
};
// A.cpp
#include "A.h"
#include "B.h"
void A::addB(B* dep) {
...
}
// B.cpp
// similar.
You probably should rethink your design, since a crcular parent-child relationship is usually a code smell.
But, you can make the compiler happy :
#include <cstdlib>
#include <cstdio>
class A
{
public:
A(){}
~A(){}
void addB(class B* dep);
void updateChild();
void print(){
printf("Printing...");
}
private:
class B* child;
};
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
void A::addB(class B* dep){
child = dep;
dep->addOwner(this);
}
void A::updateChild(){
child->printOwner();
}
int main()
{
return 0;
}
You should move B::printOwner implementation to .cpp file.