Instantiating objects and object members - c++

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.

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.

C++ Inheritance (instantiating derived class inside base class)

class MainClass
{
string _ClassName;
public:
string MainClass(string _C)
{
_ClassName = _C;
}
SubClass s1;
};
class SubClass : public MainClass
{
public:
string Method_1()
{
return a;
}
string Method_2()
{
return a;
}
};
Why is SubClass s1 not working can someone tell me please what am i missing I'm new to OOP.
I want to instantiate SubClass object inside MainClass but it doesn't seems to work.
basically, my aim is to access SubClass functions when MainClass object is instantiated in Main method something like this:
int Main()
{
MainClass M1("test");
M1.s1.Method_1(); <--------- this
}
The first problem is, that the MainClass does not know a thing about SubClass when you're trying to instantiate the object.
You need to use a forward declaration and a pointer to make it work.
Header file:
class SubClass; //Forward declaration, allows pointer.
class MainClass
{
string _ClassName;
public:
MainClass(string _C); //No return type on constructor
~MainClass();
SubClass *s1; //Size: 4 Bytes on 32bit system
protected:
MainClass();
};
class SubClass : public MainClass
{
public:
string Method_1();
string Method_2();
};
CPP file:
#include "headerFile.h"
MainClass::MainClass(string _C) :
_ClassName(_C),
s1(new SubClass) //Class definition is now known.
{
}
MainClass::MainClass() : s1(nullptr) //Nullptr -> No new object, no infinite recursion.
{
}
MainClass::~MainClass()
{
delete s1; //Do not forget to clean up your pointer.
}
string SubClass::Method_1()
{
return "a";
}
string SubClass::Method_2()
{
return "a";
}
Call:
int main()
{
MainClass M1("test");
M1.s1->Method_1(); //-> to dereference the pointer.
}
The second problem, as Richard Critten has pointed out, is an infinite recursion, which will cause your program to crash very quickly.
Each time you instantiate a SubClass, you also create a subclass, which creates yet another MainClass etc.
To circumvent this, you'll need a protected constructor, which does NOT create the subclass member.
The third problem:
You are returning a in your methods, which suggests a variable.
If you meant to return 'a', you need to put them into quotation marks.
Finally, in order to get it to compile, you'll need to write Main with a small m (int main()), otherwise the linker will complain.
However, as Mr. 'Not a number' correctly stated, the above edits only make your code compile.
What you likely are actually after however would be using virtual functions, which can be overridden by sub classes to specialize the behavior.
An example code using actual inheritance:
Header file:
class MainClass
{
string _ClassName;
public:
MainClass(string _C); //No return type on constructor
virtual ~MainClass(); //All base classes that have at least one virtual method should also have a virtual destructor, even if it is empty.
virtual void doSomething();
};
class SubClass : public MainClass
{
public:
SubClass(string className);
void doSomething();
};
CPP file:
#include "headerFile.h"
#include <stdio.h>
MainClass::MainClass(string _C) : _ClassName(_C)
{
}
MainClass::~MainClass()
{}
void MainClass::doSomething()
{
printf("Called from MainClass\n");
}
SubClass::SubClass(string className) : MainClass(className)
{
}
void SubClass::doSomething()
{
printf("Called from SubClass\n");
}
Call:
int main()
{
MainClass M1("test");
SubClass sub("SubClass");
MainClass *pointer = ⊂
M1.doSomething(); //Outputs 'Called from MainClass'.
sub.doSomething(); //Outputs 'Called from SubClass'.
pointer->doSomething(); //Also outputs 'Called from SubClass', since it points to sub and because sub overrides the behaviour from MainClass.
}
To call the parent method from the child method, you need to invoke the method from within the override with the parent class.
Example (in SubClass::doSomething): MainClass::doSomething().

C++ Child class inheriting parent class constructor

I have an assignment that requires two classes to be derived from a base class. I am having issues getting the derived classes to call the base class constructor and successfully set the inherited variables. I recreated the issue with a dummy program for simplicity since the assignment is much longer.
#include <iostream>
class ParentClass {
public:
ParentClass(int theField1, int junk);
ParentClass() {}
virtual void printField();
virtual void setField(int nf);
protected:
int field1;
};
class ChildClass : public ParentClass {
public:
ChildClass(int theField1);
void printField();
void setField(int nf);
};
ParentClass::ParentClass(int theField1, int junk) {
field1 = theField1;
}
ChildClass::ChildClass(int theField1) {
ParentClass::ParentClass(theField1, 3);
}
void ParentClass::printField() {
std::cout << "The field = " << field1 << std::endl;
}
void ChildClass::printField() {
ParentClass::printField();
std::cout << "Some other stuff." << std::endl;
}
void ParentClass::setField(int nf) {
field1 = nf;
}
void ChildClass::setField(int nf) {
ParentClass::setField(nf);
}
int main() {
ChildClass* myChild = new ChildClass(777);
ChildClass child2(888);
myChild->printField();
child2.printField();
myChild->setField(10);
myChild->printField();
child2.setField(20);
child2.printField();
return 0;
}
Running this gives me the following output:
The field = 0
Some other stuff.
The field = 4197296
Some other stuff.
The field = 10
Some other stuff.
The field = 20
Some other stuff.
Why do the first two attempts not work? Calling the constructor should be initializing the variables to the value passed as a parameter, but they are not actually set until I specifically call a mutator function. I tried a third class which used the parent mutator function in its constructor rather than the parent constructor:
class StepChild : public ParentClass {
public:
StepChild(int nf);
};
StepChild::StepChild(int nf) {
ParentClass::setField(nf);
}
The object as defined in main:
StepChild* step = new StepChild(30);
step->printField();
The output:
The field = 30
Where am I going wrong that attempting to use the parent constructor is not properly initializing these variables?
I also tried changing the parent class to be not virtual, and it worked as well, so it doesn't appear to be an issue with the parent class.
Use initialiser lists:
ParentClass::ParentClass(int theField1, int junk)
: field1(theField1)
{ }
ChildClass::ChildClass(int theField1)
: ParentClass(theField1, 3)
{ }
The following - from your code - creates a temporary ParentClass object and throws it away - that has no affect on the ChildClass object under construction:
ParentClass::ParentClass(theField1, 3); // temporary
If you make the parameters match, you can also do it the c++11 way by putting
using ParentClass::ParentClass( int, int );
in your ChildClass class definition. It is the same as invoking the parent constructor from the ChildClass constructor initialiser list, but a little less esoteric.
Not sure but I find something wrong in the way you are calling base class constructor.
try this way to call base class constructor and see if the problem is solved.

how can i move pointer of one class to another in 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;
}

Select subclass from base class...possible?

I am learning C++ and I am stuck with a problem. I need a way to use a specific subclass within base class. Does it make sense or I am using a wrong approach? SelectBrand should select the subclass, how can I do it?
Here below my simplified classes:
-----
class Protocol {
public:
Protocol() {};
~Protocol() {};
int openPort();
int readPort(char *buffer);
.....
private:
Protocol (const Protocol&);
};
int Protocol::openPort() {......};
int Protocol::readPort() {.........};
/***********************************************************************************/
class Device{
public:
Device(Protocol& port):_protocol(port){}
~Device();
virtual int getEvent(char *buffer) { return -1; }
int Device::selectBrand();
..............
protected:
Protocol& _protocol;
private:
int brand;
Device(const Device&orig);
};
Device::~Device() {}
int Device::selectBrand() {
......
switch (X)
case 1:
"use subclass Brand_B"
case 2:
"use subclass Brand_B"
.......
}
/***********************************************************************************/
class Brand_A:public Device {
public:
Brand_A(Protocol& port);
~Brand_A();
int getEvent(void *rawData);
private:
Brand_A(const Brand_A&);
};
Brand_A::Brand_A(Protocol& port):Device(port) {}
Brand_A::~Brand_A() {}
int Brand_A::getEvent(void *rawData) {
.... readPort(......);
}
/***********************************************************************************/
class Brand_B:public Device {
public:
Brand_B(Protocol& port);
~Brand_B();
int getEvent(void *rawData);
private:
Brand_B(const Brand_B&);
};
Brand_B::Brand_B(Protocol& port):Device(port) {}
Brand_B::~Brand_B() {}
int Brand_B::getEvent(void *rawData) {
.... readPort(......);
}
/* main **********************************************************/
int main(int argc, char **argv) {
Device *mydev;
char *buffer;
..............
mydev->selectBrand();
..........
mydev->getEvent(buffer);
...........
}
This is not a good idea.
Generally the answer is dynamic_cast, but invoking specific behavior of descendants from a base class is usually a bad design sign.
You can try inverting the class hierarchy and using templates.
I figured I should flesh out the comment I made above. First of all, you can check out the Wikipedia page for more information on the abstract factory pattern. Basically it allows you to access different implementations of an interface, with the implementation used determined at runtime. However, you still don't know which implementation you're getting as that is decided in the factory method that returns the implementation of the interface. As a result, you can only ever use the members in the interface and not a specific implementation. An example that uses your classes above would be something like:
class Device
{
virtual int getEvent(void *rawData) = 0;
}
class BrandA : public Device
{
// define constructors/destructors etc.
int getEvent(void *rawData)
{
// BrandA's implementation for getEvent
}
}
class BrandB : public Device
{
// define constructors/destructors etc.
int getEvent(void *rawData)
{
// BrandB's implementation for getEvent
}
}
class DeviceFactory
{
static Device *CreateDevice(/*any parameters for determining the device?*/)
{
// You probably don't want to randomly determine which implementation you use...
if ((rand() % 2) == 0)
{
return new BrandA();
}
else
{
return new BrandB();
}
}
}
int main()
{
// CreateDevice will decide which type of device we use, however we can only
// explicitly reference the members of the base class (Device).
Device *myDevice = DeviceFactory::CreateDevice();
myDevice->getEvent();
return 0;
}
It looks like you might be trying to implement something like polymorphism when C++ will do that for you. If you define virtual methods in your base class and override them in your sub classes, calls to those methods on a pointer or reference to the base type should result in the sub class' implementation being called.
For example:
class BaseClass
{
virtual void DoSomething()
{
printf("base");
}
};
class SubClass : public BaseClass
{
void DoSomething()
{
printf("sub");
}
};
int main()
{
BaseClass *myBase = new SubClass();
myBase->DoSomething(); // should print "sub" to stdout
return 0;
}
You have to know what derived type (type of subclass) you want to use when you create it so that the instance has the added functionality of the derived type. If you don't, all you get is the functionality of the base class, and you cannot treat it as anything but the base class (or anything further up the inheritance hierarchy if your base class inherits from something).
You may even want to use a member to differentiate between different instances if they're not actually doing anything different. It's hard to tell from the code example exactly what you want to do. Maybe a more specific example of what you're trying to achieve rather than how you're trying to achieve it would help.
please, let me reformulate the problem. I have 1 baseClass and some subclasses; Brand_A....Brand_N
Now, in the main() I don't know in advance which subclass I will use; this selection is demanded to a function in the baseClass which I called selectBrand. What I need is a mechanism to select and use the right subclass based on internal conditions. I want to masquerade to the main() the selected subclass. How to get this?
I implemented and tested this code; it works fine. Is it good design or can be done better?
class BehaviorBase
{
public:
virtual ~BehaviorBase() {}
virtual void DoSomethingOn(Object* obj) {}
};
class Object
{
public:
BehaviorBase* behavior;
void DoSomething();
void ChangeBehavior(int param);
~Object();
}
class BehaviorA: public BehaviorBase
{
void DoSomethingOn(Object* obj)
{
printf("Behavior A\n");
}
};
class BehaviorB: public BehaviorBase
{
string other_data;
void DoSomethingOn(Object* obj)
{
printf("Behavior B\n");
}
};
void Object::DoSomething()
{
behavior->DoSomethingOn(this);
}
Object::~Object()
{
delete behavior;
}
void Object::ChangeBehavior(int param)
{
delete behavior;
switch(param)
{
case 1: behavior = new BehaviorA; break;
case 2: behavior = new BehaviorB; break;
}
}
int main(int argc, char **argv) {
int param=1;
Object *obj;
obj= new Object;
obj->ChangeBehavior(param);
obj->DoSomething();
delete obj;
return(0);
}