Use a child function in a parent class cpp - c++

I have a parent class and a child class where the parent class uses one of the child classes in one of the parent's methods. In this method the parent uses the constructor and a method (that is a virtual method inherited from the parent) of the child, I saw another question similar to this on stackoeverflow but they did not use use methods and constructors of the child (one person mentioned the problem was easier because they only used variables of the child-class). I tried some basic class forwarding in the parent (putting class child; at the top) and that did not work.
This is the set up without any public private distinctions an attempt at address the required headers:
//foo.h
class Foo{
int x;
Foo(int i);
virtual void funA ();
void funB();
};
//foo.cpp
Foo::Foo(int i) {
x = i;
}
Foo::funA(){cout<<"Foo funA"<<endl;}
Foo::funB(){
Bar b = Bar();
b.funA();
}
//bar.h
class Bar : public Foo {
Bar(int i);
virtual void funA ();
};
//bar.cpp
Bar::Bar(int i) { x = i };
void Bar::funA(){cout<<"Bar funA"<<endl;}
I seem to be stuck on getting a the class forwarding to work. If someone could tell me how to set up my includes and class forwards that would be great!

Foo.h
class Foo {
int x;
Foo(int i);
virtual void funA();
void funB();
}
Foo.cpp
#include "Foo.h"
#include "Bar.h"
...
void Foo::funB() {
Bar b();
b.funA();
}
...
Bar.h has a dependency on Foo.h but you don't need any forward-declaration of classes (e.g. when you have a line like class Foo; that doesn't define a class body), just normal declarations. This is because Foo is not used by Bar's interface, only its implementation, so your Bar.h file can remain unchanged.

Related

C++ Different constructors use different objects

I am developing a class that has two constructors, that will use different objects. If I instance foo with no argument I want to use object bar, if I instance by foo(val) I want to use object baz.
I am getting confused how should I implement the solution. Inheritance does not seem so logical because there are differences on the functions and variables of bar and baz.
Below I present how I was thinking, basically I was setting a variable according to the called constructor. Then on my printWrapper, I was comparing this variable to know if I call bar print or baz print. One of the errors, it is due to the fact that bar and baz only have constructors with arguments. Also what I want is when I instance foo with/without argument I do not want object bar/baz created. How would you do it?
Header foo.h
class foo {
public:
foo();
foo(int val)
private:
bool object_bar;
void printWrapper();
bar b; // instance used on constructor foo()
baz c; // instance used on constructor foo(val)
}
Header bar.h
class bar {
public:
bar(int val)
private:
bool test1;
int test2;
void print();
}
Header baz.h
class baz {
public:
baz(int val)
private:
bool test1;
int test2;
int test3;
void print();
}
Source foo.cpp
foo::foo() : b(5) {
this->object_bar = true;
}
foo::foo(int val) : c(val) {
this->object_bar = false;
}
foo::printWrapper() {
if (true == this->object_bar)
b.print();
else
c.print();
}
You can use a pointer to a base abstract class as a private member of your class Foo.
And then make class Bar and Baz inherits from this base class.
Then in your class foo :
/* declaration of the base class in foo.h */
class Base;
class Foo
{
/* ... */
private:
Base *m_base;
};
and in foo.cpp :
#include "base.h"
#include "bar.h"
#include "baz.h"
Foo::Foo() {
m_base = new Bar(5);
}
Foo::Foo(int val) {
m_base = new Baz(val);
}
/* ... */

A class that can only be created by another class, without using friend

I'd like to have two non-inheritance-related and non-friends classes, class A and class B. However, i also want that class B can only be instantiated by class A, assuming that class B has a private constructor.
Is there any workaround this without having to use templates?
Rather than having a private constructor you could make your class B "private" by not placing it in any header files.
You can achieve this by using an interface class.
The client programmer can not instantiate the interface class because it is pure-virtual and it can not instantiate the implementation because it has not been declared.
The only way to instantiate it is through a factory function like this:
The public interface:
// classes.h
// pure virtual interface
struct B
{
virtual ~B() {}
virtual void func_1() = 0;
virtual void func_2() = 0;
};
class A
{
public:
// factory method
B* create_B();
};
The "private" implementation:
// classes.cpp
#include "classes.h"
// the *actual* class B
class B_Implementation
: public B
{
public:
void func_1() override
{
// do stuff
}
void func_2() override
{
// do stuff
}
};
B* A::create_B()
{
return new B_Implementation;
}
The usage:
int main()
{
A a;
auto b = std::unique_ptr<B>(a.create_B());
}
If this method is not appropriate to your situation then friend is your only friend.

How to create a derived class with same default constructor but with different value?

I have a class like this:
//class1.h
class Foo
{
private:
int m_Value;
public:
int Foo();
}
//class1.cpp
#include "class1.h"
#define CONST_VARIABLE 12
Foo::Foo()
{
m_Value = CONST_VARIABLE;
}
and a derived class:
//class2.h
#include "class1.h"
class Foo2 : public Foo
{
puplic:
Foo2();
//other functions here
}
//class2.cpp
#define CONST_VARIABLE 24;
#include "class2.h"
Foo2::Foo2() : Foo()
{
}
However, when I called
Foo a;
Foo2 b;
Those 2 (a and b) have the same m_Value (which is 12).
I knew Foo2() will call Foo() first so m_Value will take the CONST_VARIABLE in class Foo. Thus, I try re-define it but with no luck.
Since both classes are initialized the same way but with different default values and I can't add parameter to the default constructor.
How can I create a derived class with same default constructor but with different value? And in the long run, I could easily maintain or modify the code by changing the the value quickly.
You could use a protected constructor so that only derived classes can use the constructor specifying a different member value:
class Foo {
public:
Foo();
protected:
explicit Foo(int value);
private:
int m_Value;
};
Foo::Foo() :
m_Value(12)
{}
Foo::Foo(int value) :
m_Value(value)
{}
class Foo2 {
public:
Foo2();
};
Foo2::Foo2 :
Foo(24)
{}
Adhering to your requirement that there is only a default constructor, you can accomplish that with a template. Assuming you have full control over your implementation:
template <int CONST_VALUE>
class FooT {
protected:
int m_Value;
FooT () : m_Value(CONST_VALUE) {}
};
class Foo : FooT<12> {
//...
};
class Foo2 : FooT<24> {
//...
};
If Foo2 must inherit from Foo directly, you can move the parts that need to be initialized into a super parent class, and then use virtual inheritance of it by Foo so that Foo2 can initialize the super parent directly. This avoids needing to implement two constructors in Foo (one default one, and one to let Foo2 dictate initialization).
class FooBase {
protected:
int m_Value;
FooBase (int v) : m_Value(v) {}
};
class Foo : public virtual FooBase {
public:
Foo () : FooBase(12) {}
//...
};
class Foo2 : public Foo {
public:
Foo2 () : FooBase(24) {}
//...
};

Accessing nested class constructor

How can I write code for a nested class' constructor? Because the following example gives me errors
foo.h
class foo
{
public:
class bar
{
public:
bar();
~bar();
}
private:
}
foo.cpp
#include "foo.h"
foo::bar()
{
}
You have to explicitly name the constructor as a member of foo::bar, not of foo. Adjust the name like this:
foo::bar::bar() {}
// ^^^^^
Since bar is a "derived class" of foo, which means if you want to access function bar(), you need to access the class bar first.
bar() is in the namespace of foo::bar::
You need to try foo::bar::bar()
class foo {
public:
foo() : _bar(this) {}
class bar {
public:
bar(const foo* base);
~bar() {}
private:
const foo* _base;
};
private:
bar _bar;
};
foo::bar::bar(const foo* base) : _base(base) {}
add in a variable in there to also show how you can call the outer class functions inside the nested class if need as well.
As a side not you also have error with your syntax. You are missing a ; on the classes closing }.

Figuring out the class of an inheriting object

I have a linked list of Foo objects. Foo is a base class, which has several classes inherit from it. Say, classes A, B, and C.
I am cycling through this linked list and calling a method some_method, which has 3 definitions; one for each child class:
some_method(A a);
some_method(B b);
some_method(C c);
The linked list is generic, so it is of type Foo, as it has an assortment of A, B and C objects.
When I'm cycling through the linked list at current_element, calling some_method(current_element);, how can I make it call the right method? The compiler complained until I wrote a some_method that took the generic Foo, and it only calls into that method.
Depending on your requirements, you may want to consider using polymorphism. To do this, add a pure virtual method to your base node class, and move the corresponding methods to the derived classes.
class Foo
{
public:
virtual void some_method() = 0;
};
class A : Foo
{
public
virtual void some_method()
{
// move the body of some_method(A a) here
}
};
For this to work, your linked list will need Foo*, instead of Foo.
class Node
{
public:
Foo* foo;
Node* next;
};
// ...
Node* someNode = GetNode();
// Calls correct method - A::some_method, B::some_method, or C::some_method
someNode->foo->some_method();
If you can't put some_method in Foo/A/B/C, then you might want to look into the Visitor design pattern:
http://en.wikipedia.org/wiki/Visitor_pattern
This is the "double dispatch" problem. You can use the visitor pattern. Usually the Visitor is a base class so you can re-use this design for multiple problems.
#include <iostream>
class FooVisitor;
class Foo
{
public:
virtual void some_method() = 0;
virtual void visit(FooVisitor* v) = 0;
};
class A;
class B;
class FooVisitor
{
public:
virtual void visit(A* a){ std::cout << "A" << std::endl;}
virtual void visit(B* b){std::cout << "B" << std::endl;}
};
class A : public Foo
{
public:
virtual void some_method()
{
// move the body of some_method(A a) here
}
virtual void visit(FooVisitor* v) { v->visit(this);}
};
class B : public Foo
{
public:
virtual void some_method()
{
// move the body of some_method(A a) here
}
virtual void visit(FooVisitor* v) { v->visit(this);}
};
int main()
{
FooVisitor fv;
Foo* f1 = new A;
f1->visit(&fv);
Foo* f2 = new B;
f2->visit(&fv);
getchar();
}
Two ways:
1) the better way:
Reverse your design such that someMethod is a virtual method of the base class Foo and redefine it in the derived classes. As:
class Foo {
public:
virtual void someMethod() = 0;
};
class A {
public:
void someMethod() { /* implementation specific to A here */ };
};
class B {
public:
void someMethod() { /* implementation specific to B here */ };
};
class C {
public:
void someMethod() { /* implementation specific to C here */ };
};
Then calling the someMethod on a pointer to Foo will automatically call the method from the appropriate class. If that cannot be done because someMethod cannot be implemented as part of Foo or its derivatives (e.g. it needs access to private members of the class it is currently in in your design), then you might try to split this functionality apart into subproblems that can be put into virtual methods of these classes A B C.
2) the "I don't have a choice" way:
Use RTTI (Run-Time Type Identification), it is included in C++. It requires that your base class Foo has at least one virtual method. You need to #include <typeinfo>, then use typeid() on the pointer, it will return a type_info object, and you can compare its name() result with the class names A B and C. This isn't a very nice approach because it has more overhead and it breaks OOP design principles. But if that's the only option, it's fine.
RTTI is your friend here. The example given in the link will guide you further
You can call the method for the child class as a member method. For exampleA a = new A(); a.some_method() should call the correct the method. Within some_method() you can reference to object using keyword this.