how can i move pointer of one class to another in c++ - c++

I have class named CiF and I want to move in the constructor pointer of CiF to new class named Cmanager.
I tried something like this:
CiF::CiF() : Cmanager(new Cmanager(CiF THIS))
{
}
please help
thanks

The following code shows how a pointer of one class is given to another in ctor. I think thats what you're trying to achieve.
I HIGHLY recommend you on not using code like this, but you did not give enough information about your usecase and so I'm not able to give you alternatives.
You probably should take a look into smart pointers and general class design. (When giving pointers to any other class you need to control which class owns the object, deletes it etc)
class CiF;
class Cmanager
{
public:
Cmanager() :
cif_(0)
{};
void setCiF(CiF* cif)
{
cif_ = cif;
}
private:
CiF* cif_;
};
class CiF
{
public:
CiF() :
cmanager_(Cmanager())
{
cmanager_.setCiF(this);
}
private:
Cmanager cmanager_;
};

With out having a relationship between CiF and Cmanager, I think it cannot be accomplished.
#include <iostream>
class Cmanager
{
};
class Cif:public Cmanager
{
Cmanager *ptr ;
public:
bar() : ptr(this)
{
} ;
};
int main()
{
Cif obj ;
return 0;
}

Related

In C++, how to access attributes from a subclass of an object that was once created as subclass, but then copied to superclass?

Consider the code below (note: after rightful criticism I reworded the question):
#include <vector>
using std::vector;
class DataSuper {
public:
DataSuper() {}
};
class DataSub : public DataSuper {
public:
int a;
DataSub() {}
};
class Super {
public:
DataSuper data;
Super() {}
};
class Sub : public Super {
public:
Sub(DataSub i) {
data = i;
}
void test() {
// I would like to print the value of data.a
}
};
int main(int argc, char *argv[]) {
DataSub dataSub;
Super* s = new Sub(dataSub);
s->test();
delete(s);
return 0;
}
Super has an instance of DataSuper called data. Sub, a subclass of Super, has the same object data, but it is an instance of DataSub, which inherits from DataSuper.
In essence, I would like to access data.a from class Sub. I know I can do it with having data as a pointer and then use dynamic_cast, but not sure if this is good practice.
Is there a way I can avoid it WITHOUT having data as a pointer?
Super::data isn't a DataSub, but you're treating it like it is one.
Remember, in C++ a variable of object type is the object. It is not a reference or a pointer or anything like that unless you declare it to be. Super::data is a DataSuper and it can never be anything else. Forcibly pointing a DataSub& at it like you have here will not end well.
If you want to share a DataSub between your Super and Sub classes you'll need to use a pointer. For example:
class Super
{
public:
std::unique_ptr<DataSuper> data;
Super(std::unique_ptr<DataSuper> data) : data{std::move(data)} {}
};
class Sub : public Super
{
public:
using Super::Super;
private:
// Use this if you need to treat data as a DataSub
DataSub& dataSub()
{
return static_cast<DataSub&>(*data);
}
};
int main()
{
std::unique_ptr<Super> s = std::make_unique<Sub>(std::make_unique<DataSub>());
}
Demo
If you want to avoid the extra allocation for data that this requires, you could reverse the ownership direction. That is, have Sub pass a non-owning pointer to a DataSub to Super's constructor and have Sub own the object:
class Super
{
public:
Super(DataSuper* data) : data{data} {}
private:
DataSuper* data;
};
class Sub : public Super
{
public:
Sub() : Super{&data} {}
private:
DataSub data;
};
int main()
{
std::unique_ptr<Super> s = std::make_unique<Sub>();
}
Demo
Note that this approach is slightly less safe than the first approach since Sub::data isn't yet initialized when Sub's Super subobject gets initialized. If you try to use the object pointed to by Super::data in Super's constructor you'll quickly wander into the land of undefined behavior. The same goes for Super's destructor. Sub::data gets destroyed before the body of Super::~Super gets executed, so attempting to access the object pointed to by data from Super's destructor body will also result in undefined behavior.

How to store templated objects of different type in container?

Assuming I have a vector (or list or whatever container might be more suitable here) that I would like to store multiple objects (or pointers) of a templated type in:
std::vector<MyClass<double>> v;
// std::vector<MyClass<double> *> v;
Unfortunately, I want to store different templated objects in this container (and I need to access them ideally at constant time).
My first intuition was to create some sort of WrapperClass around MyClass that would internally manage any MyClass as a member variable, but it's not clear to me how I could pass along the appropriate type through to MyClass:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <vector>
using namespace std;
template<typename T>
class MyClass
{
public:
MyClass() {}
~MyClass() {}
};
// templating this of course works, but it doesn't solve my problem
template<typename T>
class WrapperClass
{
public:
WrapperClass()
{
m_object = MyClass<T>();
}
~WrapperClass() { }
private:
MyClass<T> m_object;
};
int main()
{
WrapperClass<bool> tmp = WrapperClass<bool>();
std::vector<WrapperClass<bool> *> v;
return 0;
}
So is there (A) a different container than vector that I could be using for this problem or (B) a way to select the type of MyClass in WrapperClass inside the constructor? I was thinking of something along the lines of:
class WrapperClass2
{
public:
WrapperClass2(unsigned int typeId)
{
switch (typeId)
{
case 0: m_object = new MyClass<bool>();
case 1: m_object = new MyClass<int>();
case 2: m_object = new MyClass<float>();
default: m_object = new MyClass<double>();
}
}
~WrapperClass2()
{
delete m_object;
}
private:
MyClass * m_object;
};
Another idea may be to have some parent AbstractType that I would be using in the vector, but I'm not sure how that would help with the templated type problem.
Different instantiations of a class template are completely unrelated types, so you cannot have a container that directly stores them.
You have a few options:
Keep a collection of pointers to some base class that your class template inherits from:
class Base
{
virtual ~Base {}
virtual void someMethod() const = 0;
};
template <typename T>
class MyClass : public Base
{
void someMethod() const
{
// stuff
}
};
int main()
{
std::vector<std::unique_ptr<Base>> objs;
objs.push_back(std::make_unique<MyClass<int>>());
objs.push_back(std::make_unique<MyClass<std::string>>());
for (auto& i : objs) {
i->someMethod();
}
}
This is a fairly simple approach, but it incurs a bit of runtime overhead with dynamic allocation and RTTI. Note also that someMethod can't return T, since it's a method on a parent class that doesn't know what T is.
Use some sort of type-erased wrapper like boost::any (or the forthcoming std::any in C++17).
#include <any>
#include <string>
#include <vector>
template <typename T>
class MyClass {
public:
T someMethod() const {
// stuff
return {};
}
};
void someFunctionThatTakesInt(int i) {}
void someFunctionThatTakesString(std::string s) {}
int main() {
std::vector<std::any> objs;
objs.push_back(MyClass<int>());
objs.push_back(MyClass<std::string>());
for (const auto& i : objs) {
if (i.type() == typeid(MyClass<int>)) {
auto& mc = std::any_cast<const MyClass<int>&>(i);
someFunctionThatTakesInt(mc.someMethod());
} else if (i.type() == typeid(MyClass<std::string>)) {
auto& mc = std::any_cast<const MyClass<std::string>&>(i);
someFunctionThatTakesString(mc.someMethod());
}
}
}
This approach means that you can have someMethod return T, but makes it much harder to handle retrieving objects from the vector because you have to figure out what type they are before you can do anything with them (you're essentially rolling your own RTTI).
Don't.
Rethink why you need this in the first place. Maybe another approach could work better. Maybe something with callbacks or visitors. I don't know your objective here, so I can't really say what's appropriate.
Can you do a base class and have all other classes inherit from the base class.
And you can make a list that holds a list of base class elements.
Now this is more of a pseudo example, but I hope this way would solve your problem.
Example:
class Base:
{
}
class whatever:Base
{
}
class whatever2:Base
int main()
{
list<whatever> object1;
list<whatever2> object2;
list<list<Base>> mainObj;
mainObj.push_back(object1);
mainObj.push_back(object2);
}
Now if the problem is to just have different datatypes than abstract datatypes in some container. Can't you have a Singly Link List, and have your Node generic.
Example:
template<typenameT>
struct Node
{
T data;
Node* next;
}
class LinkList
{
//Your code:
}

Dependent member initialization, when reorder is not possible

#include <iostream>
class BarParent
{
public:
int x;
virtual void fuz() = 0;
};
class BarChild : public BarParent
{
public:
BarChild(int new_x){x = new_x;}
virtual void fuz(){}
};
class FooParent
{
public:
BarParent* p_barPar;
FooParent (BarChild* new_p_bar)
{
p_barPar = new_p_bar;
std::cout << p_barPar->x << std::endl;
}
};
class FooChild: public FooParent
{
public:
BarChild barChild;
FooChild(int new_x):FooParent(&barChild), barChild(new_x){}
};
int main()
{
FooChild foo(60);
BarChild bar(99);
FooParent fooP(&bar);
}
Output:
-548726160
99
I understand why I am getting this result(undefined behavior), barChild is used before it is initiailized. My question is what is the 'right' to do handle this.
This is a case where design, not code needs to be fixed.
By your own design:
A BarChild must be constructed before FooParent.
A FooParent must be constructed before a FooChild.
A FooChild must be constructed before a BarChild.
When you want both FooParent and FooChild to refer to this same Bar object - as you're attempting in your code - design the parent class to manage it.
One example solution:
FooParent (BarChild* new_p_bar)
{
if ( new_p_bar == NULL )
new_p_bar = new BarChild;
p_barPar = new_p_bar;
std::cout << p_barPar->x << std::endl;
}
Here, FooChild doesn't need its own instance of this object.
Respect the order of initialization.
You can create a function inside BarParent to set the pointer p_barPar. Call the function in the constructor of FooChild.
Is there any reason you can't make barChild (in FooChild) a pointer as well?
I think you will have to find another example: this one is wrong because of the RAIII principle which is not enforced: FooParent holds a pointer on a value which it doesn't control. An interesting example of where this setup would fail is the slicing problem.
quick and dirty solution:
class FooChild: private BarChild, public FooParent
{
public:
FooChild(int new_x): BarChild(new_x), FooParent(this) {}
};

Instantiating objects and object members

For some reason the following doesn't crash like my program does, but I'm pretty sure it's similar in design. For one, the output's not correct. It outputs something similar to:
0x537ff4 5471612
While the main program outputs (nil) for the pointer address.
The key to the problem might be display_ in Drv.
Here's the code:
#include <iostream>
#include "debug.h"
class LCDText {
public:
int rows_;
LCDText() { rows_ = 10; };
};
class Generic {
LCDText *lcdText_;
public:
Generic(LCDText *lcdText) { lcdText_ = lcdText; };
void Setup() {
Error("%p %d", lcdText_, lcdText_->rows_);
}
};
class Display : public LCDText {
Generic *visitor_;
public:
Display(Generic *visitor) { visitor_ = visitor; };
};
class Drv : public Generic {
Display *display_;
public:
Drv() : Generic((LCDText *)display_) {
display_ = new Display((Generic *)this);
};
~Drv() { delete display_; };
};
int main()
{
Drv drv;
drv.Setup();
return 0;
}
This code:
Drv() : Generic((LCDText *)display_) {
display_ = new Display((Generic *)this);
};
first runs the parent class's ctor, with a yet-uninitialized value of display_, then independently sets display_, but, too late to change the parent class. So the pointer held by the parent class will never be set correctly. I guess you need to add a protected setter method (or make the parent-class-held pointer member itself protected).
Your Drv constructor passes the garbage, uninitialized value of Drv::display_ to Generic before initializing it in the constructor body. You can do a couple of things here, my preferred would be:
class Drv : public Generic {
Display* display() { return (Display*)lcdText_; }
public:
Drv() : Generic(new Display(this)) {}
}
Because it doesn't result in a duplicate field, but you can also have an abstract getLcdText() in Generic, which could be better if you are already using virtual methods.
In the constructor for Drv, when you first call the constructor for Generic display_ is still uninitialized. You don't new the pointer until later.

Enforce static method overloading in child class in C++

I have something like this:
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template <typename T>
int Produce()
{
return T::Lolz();
}
and
Produce<Base>();
Produce<Child>();
both return 0, which is of course correct, but unwanted. Is there anyway to enforce the explicit declaration of the Lolz() method in the second class, or maybe throwing an compile-time error when using Produce<Child>()?
Or is it bad OO design and I should do something completely different?
EDIT:
What I am basically trying to do, is to make something like this work:
Manager manager;
manager.RegisterProducer(&Woot::Produce, "Woot");
manager.RegisterProducer(&Goop::Produce, "Goop");
Object obj = manager.Produce("Woot");
or, more generally, an external abstract factory that doesn't know the types of objects it is producing, so that new types can be added without writing more code.
There are two ways to avoid it. Actually, it depends on what you want to say.
(1) Making Produce() as an interface of Base class.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
friend int Produce<Base>();
protected:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // error :'Base::Lolz' : cannot access protected member declared in class 'Base'
}
(2) Using template specialization.
template <typename T>
int Produce()
{
return T::Lolz();
}
class Base
{
public:
static int Lolz()
{
return 0;
}
};
class Child : public Base
{
public:
int nothing;
};
template<>
int Produce<Child>()
{
throw std::bad_exception("oops!");
return 0;
}
int main(void)
{
Produce<Base>(); // Ok.
Produce<Child>(); // it will throw an exception!
}
There is no way to override a static method in a subclass, you can only hide it. Nor is there anything analogous to an abstract method that would force a subclass to provide a definition. If you really need different behaviour in different subclasses, then you should make Lolz() an instance method and override it as normal.
I suspect that you are treading close to a design problem here. One of the principals of object-oriented design is the substitution principal. It basically says that if B is a subclass of A, then it must be valid to use a B wherever you could use an A.
C++ doesn't support virtual static functions. Think about what the vtable would have to look like to support that and you'll realize its a no-go.
or maybe throwing a compile-time error when using Produce<Child>()
The modern-day solution for this is to use delete:
class Child : public Base
{
public:
int nothing;
static int Lolz() = delete;
};
It helps avoid a lot of boilerplate and express your intentions clearly.
As far as I understand your question, you want to disable static method from the parent class. You can do something like this in the derived class:
class Child : public Base
{
public:
int nothing;
private:
using Base::Lolz;
};
Now Child::Lolz becomes private.
But, of course, it's much better to fix the design :)