For my new project, I wanted to use my previous code as framework to speed up prototyping by avoiding rewriting code. In the code below, Derived struct belongs to the new project and it requires to define a new member, MoreElaborateMember which has stuff relevant to the new project. I want to use the function, foo from the base project to make changes on MoreElaborateMember but I can't. How can I solve this problem without touching to the base code?
#include <cassert>
struct SimpleMember
{
int a;
};
struct MoreElaborateMember: SimpleMember
{
// lots of other stuff
};
struct Base
{
SimpleMember member;
};
struct Derived: Base
{
MoreElaborateMember member;
};
void foo(Base& base)
{
base.member.a = -1;
}
int main()
{
Base base;
Derived derived;
foo(static_cast<Base&>(derived));
assert(derived.member.a == -1);
return 0;
}
Have you considered composing MoreElaborateMember from SimpleMember instead of inheriting? Might be a bit of boiler plate but I think it would achieve what you want if I've understood correctly.
struct SimpleMember
{
int a;
};
struct MoreElaborateMember
{
MoreElaborateMember(SimpleMember& s)
: a(s.a)
{}
int& a;
int b;
};
struct Base
{
SimpleMember member;
};
struct Derived : public Base
{
Derived()
: Base()
, member(Base::member)
{}
MoreElaborateMember member;
};
void foo(Base& base)
{
base.member.a = -1;
}
int main(int, char**)
{
Derived derived;
derived.member.a = 13;
derived.member.b = 42;
assert(derived.member.a == 13);
assert(derived.member.b == 42);
foo(derived);
assert(derived.member.a == -1);
assert(derived.member.b == 42);
return 0;
}
You will be more comfortable if you use polymorphism.
#include <cassert>
struct SimpleMember
{
int a;
};
struct MoreElaborateMember : SimpleMember
{
// lots of other stuff
};
struct Base
{
protected:
SimpleMember member;
public:
virtual void set_member(int m) = 0;
};
struct Derived : public Base
{
MoreElaborateMember member;
virtual void set_member(int m)
{
Base::member.a = m;
member.a = m;
}
};
void foo(Base* base)
{
base->set_member(-1);
}
int main()
{
Derived derived;
foo(&derived);
assert(derived.member.a == -1);
return 0;
}
Related
As we know in CRTP the derived class inherit base, as final inheritance.
What if we want make the derived class not-final but the 'overriding' functions is 'final'?
Is there any way to make it with static_assert?
Code sample:
template <typename D>
struct A
{
int f()
{
return static_cast<D*>(this)->g();
}
int g();
};
struct B : A<B> // usually final, but we want it inheritable
{
int g() // but this should be 'final'
{
// TODO: ???
return 1;
}
};
struct C : B
{
int g() // this is bad
{
return 2;
}
int h(); // this is permissive
};
#include <iostream>
template <typename D>
void f(A<D>& x)
{
std::cout << x.f() << std::endl;
}
int main()
{
B b;
C c;
f(b); // OK, it's 1
f(c); // BAD, it's 1
return 0;
}
You can use final for two purposes.
From https://en.cppreference.com/w/cpp/language/final
specifies that a virtual function cannot be overridden in a derived class or that a class cannot be inherited from.
You can use
struct B : A<B>
{
virtual int g() final
{
return 1;
}
};
to allow other classes to derive from B but not able to override g().
Another potential side benefit of using final is that an optimizing compiler might be able to resolve the function call at compile time instead of resolving at run time (Thanks #JesperJuhl).
I came up with a solution by using private tag in function signature:
template <typename D>
struct A
{
struct internal_tag
{};
int f()
{
return static_cast<D*>(this)->g({});
}
int g(internal_tag);
};
struct B : A<B>
{
int g(internal_tag)
{
return 1;
}
private:
using A<B>::internal_tag;
};
struct C : B
{
// int g(internal_tag) // int g(internal_tag) is prohibited
// {
// return 2;
// }
int h();
};
I have a class derived from an interface and a friend class of the derived class. I want to access the members of derived class which is instantiated as interface. It looks like this:
Interface:
class AInterface
{
public:
virtual ~AInterface() = default;
virtual void set(int a) = 0;
};
Derived class A with friend class B:
class B;
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
private:
friend class B;
int mem = 0;
};
class B:
class B
{
public:
B()
{
a = new A();
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->mem;
}
private:
AInterface *a;
}
main:
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
The program does not compile saying AInterface has no member named 'mem'.
Do I need getter functions in the interface and implement it in A to achieve this or is there any other way to do it?
Now work
#include <iostream>
using namespace std;
class AInterface
{
public:
virtual ~AInterface() = default;
int getMem() { return mem; }
virtual void set(int a) = 0;
protected:
int mem = 0;
};
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
};
class B
{
public:
B()
{
a = new A{};
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->getMem();
}
private:
AInterface *a;
};
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
Method which is override by child and is pure, should be virtual.
If each class (child) Interface, variable int mem should be protected in interface.
Now works fine, like you want.
Add getter getMem()
Version with friend
#include <iostream>
using namespace std;
class AInterface
{
public:
virtual ~AInterface() = default;
virtual void set(int a) = 0;
protected:
friend class B;
int mem = 0;
};
class A : public AInterface
{
public:
~A() override {}
void set(int a) override
{
mem = a;
}
};
class B
{
public:
B()
{
a = new A{};
a->set(3);
}
int get_a()
{
// Access mem since it's a friend class
return a->mem;
}
private:
AInterface *a;
};
int main()
{
B *b = new B();
std::cout << b->get_a() << std::endl;
return 0;
}
In your class B.
class B
{
//...
int get_a()
{
return a->mem; // but a is a AInterface* !!!
}
private:
AInterface *a; // That's not an A*, but an AInterface*
};
You have 2 options.
use dynamic_cast<>
int B::get_a()
{
A* p = dynamic_cast<A*>(a);
if (p)
return p->mem;
// a is not an A*, it's another AInterface*-type object !!!
// What should you do?
throw something_or_other(); // throw?
return -1; // return an error code?
}
// or maybe add.. so you can check for errors before calling get_a()
A* B::get_A_ptr() const
{
return dynamic_cast<A*>(a);
}
dynamic_cast works fine, but can slow down your app if you need to make frequent reads of a->mem.
Store a in an A*, which is probably what you meant to do from the start...
class B
{
// ...
private:
A* a; // now a->A::mem is visible.
};
Since you explicitly call new A in B's constructor, I think option 2 is better for your case.
I have an old factory implementation in c++, and I want to use unique pointers instead of raw pointers in it. A minimal example of my code is as follows. I have a base class A, and a derived class B. In main(), I pass 1 to the create method in A, and the type of b1 is now changed to B.
#include <iostream>
#include <map>
class A {
public:
A() {}
virtual void Foo() {}
std::map<int, A *> ®isterType() {
static std::map<int, A *> map_instance;
return map_instance;
}
A *create(int n) { return registerType()[n]; }
};
class B : A {
public:
B() { registerType()[1] = this; }
void Foo() { std::cout << "I am B!\n"; }
};
static B b0;
int main() {
A *b1 = new A();
b1 = b1->create(1);
b1->Foo();
return 0;
}
Now if I want to change raw pointers to unique pointers, I naturally get a collection of errors (the following code results in errors):
#include <iostream>
#include <map>
#include <memory>
class A {
public:
A() {}
virtual void Foo() {}
std::map<int, std::unique_ptr<A>> ®isterType() {
static std::map<int, std::unique_ptr<A>> map_instance;
return map_instance;
}
std::unique_ptr<A> create(int n) { return registerType()[n]; }
};
class B : A {
public:
B() { registerType()[1](this); }
void Foo() { std::cout << "I am B too!\n"; }
};
static B b0;
int main() {
std::unique_ptr<A> b1(new A());
b1 = b1->create(1);
b1->Foo();
return 0;
}
The errors are:
In member function 'std::unique_ptr<A> A::create(int)':
use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = A; _Dp = std::default_delete<A>]'
std::unique_ptr<A> create(int n) { return registerType()[n]; }
In constructor 'B::B()':
no match for call to '(std::map<int, std::unique_ptr<A> >::mapped_type {aka std::unique_ptr<A>}) (B* const)'
B() { registerType()[1](this); }
^
So I want to know:
Were unique pointers intended to be used in cases like mine? (I assume the response should be yes!)
I need to pass this as a unique_ptr type to the registerType method. How I can pass the ownership of the pointer to the current instance (this keyword) to a unique_ptr? (If it is possible or was intended to be possible.)
If it is a good practice to use unique pointers here, how I should implement it?
First of all, if someone wants to implement a factory pattern, an acceptable way of doing it with raw pointers is as follows:
#include <iostream>
#include <map>
class A;
class A_Factory {
public:
A_Factory() {}
virtual A *create() = 0;
};
class A {
public:
A() {}
static void registerType(int n, A_Factory *factory) {
get_factory_instance()[n] = factory;
}
static A *create(int n) {
A *A_instance = get_factory_instance()[n]->create();
return A_instance;
}
virtual void setMyID(int n) {}
virtual void I_am() { std::cout << "I am A\n"; }
virtual ~A() {}
protected:
int MyID;
static std::map<int, A_Factory *> &get_factory_instance() {
static std::map<int, A_Factory *> map_instance;
return map_instance;
}
};
class B : public A {
public:
B() {}
void Foo() {}
void I_am() { std::cout << "I am B " << MyID << "\n"; }
void setMyID(int n) { MyID = n; }
~B() {}
private:
};
class B_Factory : public A_Factory {
public:
B_Factory() { A::registerType(1, this); }
A *create() { return new B(); }
};
static B_Factory b0_factory;
void caller() {}
int main() {
A *b1 = A::create(1);
A *b2 = A::create(1);
b1->setMyID(10);
b2->setMyID(20);
b1->I_am();
b2->I_am();
delete b1;
delete b2;
return 0;
}
A is the base class, and B is the derived one. If we pass 1 to A::create(int n), an object of type B will be produced. The memory is managed manually and there would be no memory leak.
Concerning the questions in the post:
YES. unique_ptr is awesome; use them wherever you can!
With the design presented in the question, passing the ownership of this was somehow necessary. I cannot think of a way to pass the ownership of this. With the design presented in the answer, it is not necessary to pass the ownership of this.
Implement the unique_ptr in the above factory pattern as below:
#include <iostream>
#include <map>
#include <memory>
class A;
class A_Factory {
public:
A_Factory() {}
virtual std::unique_ptr<A> create_unique() = 0;
};
class A {
public:
A() {}
static void registerType(int n, A_Factory *factory) {
get_factory_instance()[n] = factory;
}
static std::unique_ptr<A> create_unique(int n) {
std::unique_ptr<A> A_instance =
std::move(get_factory_instance()[n]->create_unique());
return A_instance;
}
virtual void setMyID(int n) {}
virtual void I_am() { std::cout << "I am A\n"; }
virtual ~A() {}
protected:
int MyID;
static std::map<int, A_Factory *> &get_factory_instance() {
static std::map<int, A_Factory *> map_instance;
return map_instance;
}
};
class B : public A {
public:
B() {}
void Foo() {}
void I_am() { std::cout << "I am B " << MyID << "\n"; }
void setMyID(int n) { MyID = n; }
~B() {}
private:
};
class B_Factory : public A_Factory {
public:
B_Factory() { A::registerType(1, this); }
std::unique_ptr<A> create_unique() {
std::unique_ptr<A> ptr_to_B(new B);
return ptr_to_B;
}
};
static B_Factory b0_factory;
void caller() {}
int main() {
std::unique_ptr<A> b1 = std::move(A::create_unique(1));
std::unique_ptr<A> b2 = std::move(A::create_unique(1));
b1->setMyID(10);
b2->setMyID(20);
b1->I_am();
b2->I_am();
return 0;
}
As you can see, no manual memory management is necessary and the memory management is handled by the unique_ptr.
My problem is the following:
int main()
{
Base* derivedobject = new Derived1();
derivedobject->GetProperties()-> ???
return 0;
}
//********************
// BaseClass.h
//********************
struct PropertyStruct
{
int x;
};
class Base
{
public:
Base();
~Base();
virtual PropertyStruct GetProperties() = 0;
private:
};
//********************
// DerivedClass1.h
//********************
struct PropertyStruct
{
int y;
};
class Derived1 : public Base
{
public:
Derived1();
~Derived1();
PropertyStruct GetProperties() { return myOwnDifferentProperties; };
private:
};
//********************
// DerivedClass2.h
//********************
struct PropertyStruct
{
float z;
};
class Derived2 : public Base
{
public:
Derived2();
~Derived2();
PropertyStruct GetProperties() { return myOwnDifferentProperties };
private:
};
If I do it like that I'm going to get an error saying that PropertyStruct is a redefinition. If I use a namespace or rename the struct inside the derived class I am then going to get an error telling me that the return type is not the same as defined by Base.
If I define the virtual functions return type as a pointer it compiles, though the next problem when accessing the function "GetProperties" from the main method (in this example) the base object does not know what variables are inside the struct of the derived class.
Is there any way I can realize this ?
That I can get the different properties of each derived object but using the base class object ?
As others have mentioned, there are ways to achieve your goals here but ultimately you will find yourself writing code like the following:
Base * object = ...;
if object is Derived1 then
get Property1 and do something with it
else if object is Derived2 then
get Property2 and do something with it
This is an anti-pattern in object-oriented programming. You already have a class hierarchy to represent the differences between the various derived types. Rather than extracting the data from your objects and processing it externally, consider adding a virtual function to the base class and letting the derived classes do the processing.
class Base
{
public:
virtual void DoSomething() = 0;
};
class Derived1 : Base
{
public:
void DoSomething()
{
// use myOwnDifferentProperties as necessary
}
private:
PropertyStruct myOwnDifferentProperties;
};
If it's not appropriate to put the required processing in the derived classes (i.e. if it would introduce unwanted responsibilities) then you may want to consider the Visitor Pattern as a way to extend the functionality of your hierarchy.
Since template functions cannot be virtual you can use hierarchy of your properties. It's only one way, no other ways. For get elements of derived Properties you should use virtual getter functions.
struct BaseProp
{
virtual ~BaseProp() { }
virtual boost::any getProperty() const = 0;
};
struct PropertyStruct : BaseProp
{
boost::any getProperty() const { return x; }
private:
int x;
};
struct PropertyStruct2 : BaseProp
{
boost::any getProperty() const { return y; }
private:
float y;
};
class Base
{
public:
virtual std::shared_ptr<BaseProp> GetProperties() const = 0;
virtual ~Base() { }
}
class Derived
{
public:
std::shared_ptr<BaseProp> GetProperties() const { return new PropertyStruct(); }
};
class Derived2
{
public:
std::shared_ptr<BaseProp> GetProperties() const { return new PropertyStruct2(); }
};
You can use template class to do that:
struct PropertyStruct1 {
float f;
};
struct PropertyStruct2 {
int i;
};
template<class T>
class A{
public:
T GetProperties() {return mProps;}
private:
T mProps;
};
int main (int argc, const char * argv[]) {
A<PropertyStruct1> a1;
int f = a1.GetProperties().f;
A<PropertyStruct2> a2;
int i = a2.GetProperties().i;
return 0;
}
I like the results of this code but i was curious, is it possible to call B::VFunc() from main()? I know writing B::VFunc(); inside of C will call it but is it possible to call the function from outside of the object?
http://ideone.com/Dg8aa
#include <cstdio>
class I { public: virtual void VFunc()=0; };
class B : public I { public: void VFunc() { printf("B\n"); } };
class C : public B { public: void VFunc() { printf("C\n"); } };
int main(){
C v;
B&i = v;
i.VFunc();
}
output:
C
This will do it:
#include <cstdio>
class I { public: virtual void VFunc()=0; };
class B : public I { public: void VFunc() { printf("B\n"); } };
class C : public B { public: void VFunc() { printf("C\n"); } };
int main(){
C v;
B&i = v;
i.B::VFunc();
}
Example: http://ideone.com/MfyYJ
You can resort to slicing:
C v;
B i = (B)v;
http://ideone.com/YVI2T
The dynamic type of v is lost, so B::VFunc is called.