upcasting variable in derived class c++ - c++

How to change the type of a inherited variable in the derived class?
I have the following classes:
class Position;
class StonePosition;
class Position {
public:
Position() {}
};
class StonePosition : public Position {
int count;
public:
StonePosition(const int count) { this->count = count; }
int getCount() { return this->count; }
void setCount(int count) { this->count = count; }
friend ostream& operator<<(ostream&, StonePosition);
};
class Board {
protected:
Position* crrPos;
public:
Board() { }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
class StoneBoard : public Board {
public:
StoneBoard(const int &count) { this->crrPos=new StonePosition(count); } //<----------------
StonePosition* getCrrPos() { return (StonePosition*)crrPos; }
void setCrrPos(StonePosition* pos) { crrPos=pos; }
};
Place in which the problem is marked by an arrow. I need to change the type of a variable from Position to StonePosition in the StoneBoard class. I found an option that can be used upcasting, but it works only within a single method, and I need to change the variable for the entire class.
The problem was solved, look at my answer.

The variable "crrPos" is not of type Position it is of type pointer to Position and this is significant because a pointer to Position can point to a Position or a class derived from Position without losing anything.
If you design your classes well, and make use of virtual functions, you can usually avoid the need to upcast entirely.
#include <iostream>
class Base {
public:
virtual void foo() { std::cout << "Base::foo()\n"; }
virtual bool isDerived() const { return false; }
};
class Derived : public Base {
public:
void foo() override { std::cout << "Derived::foo()\n"; }
bool isDerived() const { return true; }
};
int main() {
Base* crrPos = new Derived;
crrPos->foo();
bool isDerived = crrPos->isDerived();
std::cout << isDerived << '\n';
delete crrPos;
}
Live demo: http://ideone.com/UKcBaA

The problem has been solved, I just use the projection ((StonePosition*)Position*):
#include <iostream>
using namespace std;
class Position;
class StonePosition;
class Position {
public:
Position() {}
};
class StonePosition : public Position {
int count;
public:
StonePosition(const int count) { this->count = count; }
int getCount() { return this->count; }
void setCount(int count) { this->count = count; }
friend ostream& operator<<(ostream&, StonePosition);
};
template <typename TPos> class TBoard {
protected:
TPos* crrPos;
public:
TBoard() { }
TPos* getCrrPos() { return crrPos; }
void setCrrPos(TPos* pos) { crrPos=pos; }
};
class Board {
protected:
Position* crrPos;
public:
Board() { }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
class StoneBoard : public Board {
public:
StoneBoard(const int &count) { this->crrPos=new StonePosition(count); }
Position* getCrrPos() { return crrPos; }
void setCrrPos(Position* pos) { crrPos=pos; }
};
int main(){
StoneBoard s(7);
cout<<((StonePosition*)s.getCrrPos())->getCount();//<----right here
system("pause");
return 0;
}
And its working nice :)

Related

Issue with polymorphism with smart pointers and vectors c++

I am currently trying to learn c++ and I am having an issue when trying to create a vector which iterates through several different objects whom all inherit from the same base class with smart pointers.
I parse a file and create the objects and insert them into the vector depending on the character parsed but I keep getting the error:
Error C2664 'std::unique_ptr<Test *,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': cannot convert argument 1 from 'std::unique_ptr<Test2,std::default_delete<_Ty>>' to 'std::nullptr_t'"
Code is as follows:
class Test {
public:
virtual ~Test(){}
virtual int update() {}
};
class Test2 : public Test {
private:
int a;
public:
Test2() {
}
Test2(int n) {
a = n;
}
int update() override {
return a;
}
};
class Test3 : public Test {
private:
int a;
public:
Test3() {
}
Test3(int n) {
a = n;
}
int update() override {
return a;
}
};
class Test4 : public Test {
private:
int a;
public:
Test4() {
}
Test4(int n) {
a = n;
}
int update() override {
return a;
}
};
class manager {
private:
std::vector<std::unique_ptr<Test*>> vList;
std::ifstream lvlFile;
public:
std::string tmp;
manager() {
}
~manager() {
}
void init(const char *path) {
lvlFile.open(path, 0);
while (lvlFile.eof() != true) {
std::getline(lvlFile, tmp);
for (char& a : tmp) {
switch (a) {
case 'w':
vList.emplace_back(std::make_unique<Test2>(2));
break;
case 'g':
vList.emplace_back(std::make_unique<Test3>(3));
break;
}
}
}
}
void print() {
for (auto& i : vList) {
std::cout << (*i)->update() << std::endl;
}
}
};
manager *m;
int main() {
m = new manager();
m->init("lvl.txt");
_getch();
}
Maybe I have misunderstood something crucial here but I have been looking around and found no real answers so any pointers to this would be most welcome!
Change std::vector<std::unique_ptr<Test*>> to std::vector<std::unique_ptr<Test>>.
std::unique_ptr<Test*> is a pointer to pointer (Test**).

c++ access array data of shared library

I am coding in stm32. Basically, I want to access a bool array data from another library. This is a header file of AP_Tmxk_LIDARScanner library stored data in scan.isObstacle which is a bool array. Also I made a return function named getObstacle(). Another library named AP_Tmxk_VFH to access data from getObstacle(). Is that ok? Or which is the way to copy that array in AP_Tmxk_VFH. Thanks for your help.
AP_Tmxk_LIDARScanner
class AP_Tmxk_LIDARScanner {
private:
struct{
bool isObstacle[180] = {}; //1: unsafe; 0:safe
bool available = false;
}scan;
public:
AP_Tmxk_LIDARScanner();
void init();
void update();
bool getAvailable() const{
return scan.available;
}
bool getObstacle() const{
return scan.isObstacle;
}
};
AP_Tmxk_VFH.h
class AP_Tmxk_VFH {
private:
struct{
bool Certain_Value[180] = {};
}sector;
const AP_Tmxk_LIDARScanner &_lidarscanner;
public:
// Constructor
AP_Tmxk_VFH(const AP_Tmxk_LIDARScanner &_lidarscanner);
void init();
void update();
};
AP_Tmxk_VFH.cpp
AP_Tmxk_VFH::AP_Tmxk_VFH(const AP_Tmxk_LIDARScanner &lidarscanner) :
_lidarscanner(lidarscanner)
{}
void AP_Tmxk_VFH::update()
{
if(_lidarscanner.getAvailable()){
sector.Certain_Value = _lidarscanner.getObstacle()
}
}
Here I modfiy my code format.
AP_Tmxk_LIDARScanner.h
class AP_Tmxk_LIDARScanner {
private:
struct{
bool isObstacle[180]= {}; //1: unsafe; 0:safe
bool available = false;
}scan;
public:
AP_Tmxk_LIDARScanner();
void init();
void update();
bool getAvailable() const{
return scan.available;
}
void getObstacle(int (&array)[180]);
};
AP_Tmxk_LIDARScanner.cpp
void AP_Tmxk_LIDARScanner::getObstacle(int (&array)[180])
{
for(int i=0; i<180; i++){
if(scan.isObstacle[i]){
array[i] = (array[i]+1 >= 5) ? 5 : array[i]+1;
}
else{
array[i] = (array[i]-1 >= 0) ? array[i]-1 : 0;
}
}
}
AP_Tmxk_VFH.h
class AP_Tmxk_VFH {
private:
struct{
int Certain_Value[180] = {};
}sector;
class AP_Tmxk_LIDARScanner &_lidarscanner;
public:
// Constructor
AP_Tmxk_VFH(class AP_Tmxk_LIDARScanner &_lidarscanner);
void init();
void update();
};
AP_Tmxk_VFH.cpp
AP_Tmxk_VFH::AP_Tmxk_VFH(class AP_Tmxk_LIDARScanner &lidarscanner) :
_lidarscanner(lidarscanner)
{}
void AP_Tmxk_VFH::update()
{
if(_lidarscanner.getAvailable()){
_lidarscanner.getObstacle(sector.Certain_Value);
}
}

Class factory to create derived classes c++

I'm currently learning about class factory patterns with C++. I keep having errors while trying to implement the factory. Suppose I have an abstract class and two derived classes. What I want the factory to do is to create a new object of the base class like so: Ball *sc = new SoccerBall();
I am not sure on how to implement this, I have tried but of no avail. What do I need to fix?
class Ball
{
public:
Ball();
virtual ~Ball();
virtual int getSize() const = 0;
virtual void setBallSize(int s) = 0;
virtual string ballManufacturer() const = 0;
protected:
int ballSize;
}
class Soccerball:public Ball
{
public:
Soccerball();
Soccerball(int size);
~Soccerball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class Soccerball:public Ball
{
public:
Soccerball();
Soccerball(int size);
~Soccerball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class Basketball:public Ball
{
public:
Basketball();
Basketball(int size);
~Basketball();
int getSize() const;
void setBallSize(int s);
string ballManufacturer() const;
}
class BallFactory
{
public:
Ball* createBall(string s)
{
if(s == "Soccer")
{
return new Soccerball(5);
}
if(s == "Basket")
{
return new Basketball(6);
}
}
}
This how your code will work, but above when you are posting a question you should provide "Short Self Contained Correct Code" and make easy for people to understand your problem easily.
#include <iostream>
using namespace std;
class Ball
{
public:
Ball()
{
cout<<"Ball ctr"<<endl;
}
virtual ~Ball()
{
}
virtual int getSize() const = 0;
virtual void setBallSize(int s) = 0;
virtual string ballManufacturer() const = 0;
protected:
int ballSize;
};
class Soccerball:public Ball
{
public:
Soccerball()
{
cout<<"create Default Soccer Ball "<<endl;
}
Soccerball(int size)
{
cout<<"create Soccer Ball "<<size<<endl;
}
~Soccerball()
{
}
int getSize() const
{
return ballSize;
}
void setBallSize(int s)
{
ballSize = s;
}
string ballManufacturer() const
{
return "";
}
};
class Basketball:public Ball
{
public:
Basketball()
{
cout<<"create default Baseket Ball "<<endl;
}
Basketball(int size)
{
cout<<"create Baseket Ball "<<size<<endl;
}
~Basketball()
{
}
int getSize() const
{
return ballSize;
}
void setBallSize(int s)
{
ballSize = s;
}
string ballManufacturer() const
{
return "";
}
};
class BallFactory
{
public:
//Factory method
static Ball* createBall(string s)
{
if(s == "Soccer")
{
return new Soccerball(5);
}
if(s == "Basket")
{
return new Basketball(6);
}
}
};
int main()
{
Ball* ptr = BallFactory::createBall("Soccer");
return 0;
}
But you also need to understand how Factory design pattern works and how a namesake virtual constructor is created and why you would use a parameterized factory. Or could you use a template factory.

Adapter pattern in C++, with non-virtual adapted methods

I want to create an adapter class in C++, but the interface that I want to adapt to has several non-virtual methods. Can I still use the regular adapter pattern?
#include <iostream>
using namespace std;
class NewInterface{
public:
int methodA(){ cout << "A\n"; }
virtual int methodB(){ cout << "B\n"; }
};
class OldInterface{
public:
int methodC(){ cout << "C\n"; }
int methodD(){ cout << "D\n"; }
};
class Old2NewAdapter: public NewInterface {
public:
Old2NewAdapter( OldInterface* a ){ adaptee = a; }
int methodA(){ return adaptee->methodC(); }
int methodB(){ return adaptee->methodD(); }
private:
OldInterface* adaptee;
};
int main( int argc, char** argv )
{
NewInterface* NI = new Old2NewAdapter( new OldInterface() );
NI->methodA();
NI->methodB();
return 0;
}
If I have this setup, the output will be "A D" instead of "C D" as it should.
So how can I adapt OldInterface to NewInterface, without rewriting NewInterface so that all methods are virtual?
Can you introduce another class? If you can then you can replace functions that use a NewInterface with an even NewerInterface:
class NewerInterface
{
public:
int methodA()
{
// preconditions
int const result = doMethodA();
// postconditions
return result;
}
int methodB()
{
// preconditions
int const result = doMethodB();
// postconditions
return result;
}
private:
virtual int doMethodA() = 0;
virtual int doMethodB() = 0;
};
class Old2NewerInterface : public NewerInterface
{
public:
explicit Old2NewerInterface(OldInterface& x) : old_(&x)
private:
virtual int doMethodA() { return old_->methodC(); }
virtual int doMethodB() { return old_->methodD(); }
private:
OldInterface* old_;
};
class New2NewerInterface : public NewerInterface
{
public:
explicit New2NewerInterface(NewInterface& x) : new_(&x)
private:
virtual int doMethodA() { return new_->methodA(); }
virtual int doMethodB() { return new_->methodB(); }
private:
NewInterface* new_;
};

Dynamic Object in C++?

I realize that I'll most likely get a lot of "you shouldn't do that because..." answers and they are most welcome and I'll probably totally agree with your reasoning, but I'm curious as to whether this is possible (as I envision it).
Is it possible to define a type of dynamic/generic object in C++ where I can dynamically create properties that are stored and retrieved in a key/value type of system? Example:
MyType myObject;
std::string myStr("string1");
myObject.somethingIJustMadeUp = myStr;
Note that obviously, somethingIJustMadeUp is not actually a defined member of MyType but it would be defined dynamically. Then later I could do something like:
if(myObject.somethingIJustMadeUp != NULL);
or
if(myObject["somethingIJustMadeUp"]);
Believe me, I realize just how terrible this is, but I'm still curious as to whether it's possible and if it can be done in a way that minimizes it's terrible-ness.
C++Script is what you want!
Example:
#include <cppscript>
var script_main(var args)
{
var x = object();
x["abc"] = 10;
writeln(x["abc"]);
return 0;
}
and it's a valid C++.
You can do something very similar with std::map:
std::map<std::string, std::string> myObject;
myObject["somethingIJustMadeUp"] = myStr;
Now if you want generic value types, then you can use boost::any as:
std::map<std::string, boost::any> myObject;
myObject["somethingIJustMadeUp"] = myStr;
And you can also check if a value exists or not:
if(myObject.find ("somethingIJustMadeUp") != myObject.end())
std::cout << "Exists" << std::endl;
If you use boost::any, then you can know the actual type of value it holds, by calling .type() as:
if (myObject.find("Xyz") != myObject.end())
{
if(myObject["Xyz"].type() == typeid(std::string))
{
std::string value = boost::any_cast<std::string>(myObject["Xyz"]);
std::cout <<"Stored value is string = " << value << std::endl;
}
}
This also shows how you can use boost::any_cast to get the value stored in object of boost::any type.
This can be a solution, using RTTI polymorphism
#include <map>
#include <memory>
#include <iostream>
#include <stdexcept>
namespace dynamic
{
template<class T, class E>
T& enforce(T& z, const E& e)
{ if(!z) throw e; return z; }
template<class T, class E>
const T& enforce(const T& z, const E& e)
{ if(!z) throw e; return z; }
template<class Derived>
class interface;
class aggregate;
//polymorphic uncopyable unmovable
class property
{
public:
property() :pagg() {}
property(const property&) =delete;
property& operator=(const property&) =delete;
virtual ~property() {} //just make it polymorphic
template<class Interface>
operator Interface*() const
{
if(!pagg) return 0;
return *pagg; //let the aggregate do the magic!
}
aggregate* get_aggregate() const { return pagg; }
private:
template<class Derived>
friend class interface;
friend class aggregate;
static unsigned gen_id()
{
static unsigned x=0;
return enforce(++x,std::overflow_error("too many ids"));
}
template<class T>
static unsigned id_of()
{ static unsigned z = gen_id(); return z; }
aggregate* pagg;
};
template<class Derived>
class interface: public property
{
public:
interface() {}
virtual ~interface() {}
unsigned id() const { return property::id_of<Derived>(); }
};
//sealed movable
class aggregate
{
public:
aggregate() {}
aggregate(const aggregate&) = delete;
aggregate& operator=(const aggregate&) = delete;
aggregate(aggregate&& s) :m(std::move(s.m)) {}
aggregate& operator=(aggregate&& s)
{ if(this!=&s) { m.clear(); std::swap(m, s.m); } return *this; }
template<class Interface>
aggregate& add_interface(interface<Interface>* pi)
{
m[pi->id()] = std::unique_ptr<property>(pi);
static_cast<property*>(pi)->pagg = this;
return *this;
}
template<class Inteface>
aggregate& remove_interface()
{ m.erase[property::id_of<Inteface>()]; return *this; }
void clear() { m.clear(); }
bool empty() const { return m.empty(); }
explicit operator bool() const { return empty(); }
template<class Interface>
operator Interface*() const
{
auto i = m.find(property::id_of<Interface>());
if(i==m.end()) return nullptr;
return dynamic_cast<Interface*>(i->second.get());
}
template<class Interface>
friend aggregate& operator<<(aggregate& s, interface<Interface>* pi)
{ return s.add_interface(pi); }
private:
typedef std::map<unsigned, std::unique_ptr<property> > map_t;
map_t m;
};
}
/// this is a sample on how it can workout
class interface_A: public dynamic::interface<interface_A>
{
public:
virtual void methodA1() =0;
virtual void methodA2() =0;
};
class impl_A1: public interface_A
{
public:
impl_A1() { std::cout<<"creating impl_A1["<<this<<"]"<<std::endl; }
virtual ~impl_A1() { std::cout<<"deleting impl_A1["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_A2: public interface_A
{
public:
impl_A2() { std::cout<<"creating impl_A2["<<this<<"]"<<std::endl; }
virtual ~impl_A2() { std::cout<<"deleting impl_A2["<<this<<"]"<<std::endl; }
virtual void methodA1() { std::cout<<"interface_A["<<this<<"]::methodA1 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodA2() { std::cout<<"interface_A["<<this<<"]::methodA2 on impl_A2 in aggregate "<<get_aggregate()<<std::endl; }
};
class interface_B: public dynamic::interface<interface_B>
{
public:
virtual void methodB1() =0;
virtual void methodB2() =0;
};
class impl_B1: public interface_B
{
public:
impl_B1() { std::cout<<"creating impl_B1["<<this<<"]"<<std::endl; }
virtual ~impl_B1() { std::cout<<"deleting impl_B1["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B1 in aggregate "<<get_aggregate()<<std::endl; }
};
class impl_B2: public interface_B
{
public:
impl_B2() { std::cout<<"creating impl_B2["<<this<<"]"<<std::endl; }
virtual ~impl_B2() { std::cout<<"deleting impl_B2["<<this<<"]"<<std::endl; }
virtual void methodB1() { std::cout<<"interface_B["<<this<<"]::methodB1 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
virtual void methodB2() { std::cout<<"interface_B["<<this<<"]::methodB2 on impl_B2 in aggregate "<<get_aggregate()<<std::endl; }
};
int main()
{
dynamic::aggregate agg1;
agg1 << new impl_A1 << new impl_B1;
dynamic::aggregate agg2;
agg2 << new impl_A2 << new impl_B2;
interface_A* pa = 0;
interface_B* pb = 0;
pa = agg1; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
agg2 = std::move(agg1);
pa = agg2; if(pa) { pa->methodA1(); pa->methodA2(); }
pb = *pa; if(pb) { pb->methodB1(); pb->methodB2(); }
return 0;
}
tested with MINGW4.6 on WinXPsp3
Yes it is terrible. :D
It had been done numerous times to different extents and success levels.
QT has Qobject from which everything related to them decends.
MFC has CObject from which eveything decends as does C++.net
I don't know if there is a way to make it less bad, I guess if you avoid multiple inheritance like the plague (which is otherwise a useful language feature) and reimplement the stdlib it would be better. But really if that is what you are after you are probably using the wrong language for the task.
Java and C# are much better suited to this style of programming.
#note if I have read your question wrong just delete this answer.
Check out Dynamic C++