Copy constructor for derived class from base pointer - c++

I have looked all around and can't find the answer to my question anywhere. I am trying to use a copy constructor of a derived class from a pointer array of base classes. The only thing I have learned is I should probably use dynamic_cast but cant get that working.
This is the important parts of my code so far (original is way to big since I have 16 different files but this should be enough).
EDIT: The error I receive doing it this way is |26|error: cannot dynamic_cast '& properties[0]' (of type 'class Property**') to type 'class Commercial*' (source is not a pointer to class)|
#include "rentals.h"
#include "commercial.h"
#include "sales.h"
#include "comSales.h"
#include "resSales.h"
#include "resRentals.h"
#include "comRentals.h"
const int MAX_PROPERTIES = 5;
int main(void) {
int i;
Property *properties[MAX_PROPERTIES];
properties[0] = new Commercial("Notting Hill McDonalds", "4 Gardiner Road",
"Notting Hill", 5000, "Li3000");
properties[1] = new ResRentals("Janet Dalgleish", "30 Firhill Court",
"Mary Hill", 4000, 500.00, 300.00, 4);
properties[2] = new Commercial(dynamic_cast<Commercial*>(properties[0])); // <-- the copy constructor I can not get to work.
delete[] properties;
return 0;
}
commercial.cpp file
#include "property_a.h"
#include "commercial.h"
Commercial::Commercial() : Property() {
owner = "NULL";
address = "NULL";
suburb = "NULL";
postcode = 0;
license = "NULL";
}
Commercial::Commercial(string theOwner, string theAddress,
string theSuburb, int thepostCode,
string theLicense): Property(theOwner, theAddress,
theSuburb, thepostCode), license(theLicense) {}
Commercial::~Commercial() {}
Commercial::Commercial(const Commercial& orig) : Property(orig),
license(orig.getLicense()) {}
void Commercial::print() {
cout << getOwner() << endl;
cout << getAddress() << endl;
cout << getSuburb() << endl;
cout << getPostcode() << endl;
cout << getLicense() << endl;
}
commercial.h file
#ifndef __COMMERCIAL_H__
#define __COMMERCIAL_H__
#include "property_a.h"
class Commercial : public virtual Property
{
protected:
string license;
public:
Commercial();
Commercial(string theOwner, string theAddress, string theSuburb,
int thepostCode, string theLicense);
~Commercial() ;
Commercial(const Commercial& orig);
void input() ; // Data input for a Shop object
void print() ; // Data output for a Shop object
string getLicense() const {return license;}; //Note the use of const
void setLicense(string theLicense) {license = theLicense;};
};
property_a.cpp file
#include "property_a.h"
Property::Property(){
owner = "NULL";
address = "NULL";
suburb = "NULL";
postcode = 0;
}
Property::Property(string theOwner, string theAddress,
string theSuburb, int thepostCode):
owner(theOwner), address(theAddress),
suburb(theSuburb), postcode(thepostCode){}
Property::~Property() {}
Property::Property(const Property& orig) :
owner(orig.getOwner()), address(orig.getAddress()),
suburb(orig.getSuburb()), postcode(getPostcode()) {}
property_a.h file
#ifndef __PROPERTY_A_H__
#define __PROPERTY_A_H__
/*TODO REQUIRED HEADER FILES AND NAMESPACES*/
#include <string>
#include "utility1.h"
class Property
{
protected:
string owner;
string address;
string suburb;
int postcode;
public:
Property();
Property(string theOwner, string theAddress, string theSuburb, int thepostCode);
virtual ~Property();
Property(const Property& orig);
virtual void input() ; // Data input for a Property object
virtual void print() ; // Data output for a Property object
string getOwner() const {return owner;}; //Note the use of const
string getAddress() const {return address;};
string getSuburb() const {return suburb;};
int getPostcode() const {return postcode;};
void setOwner(string newOwner) {owner = newOwner;};
void setAddress(string newAddress) {address = newAddress;};
void setSuburb( string newSuburb) {suburb = newSuburb;};
void setPostcode(int newPostcode) {postcode = newPostcode;};
};
#endif
I hope this is enough details

properties[2] = new Commercial(dynamic_cast(properties[0])); // <-- the copy constructor I can not get to work.
This is casting properties[0] to Commercial*. But this isn't the signature of your copy constructor. Therefore, you need new Commercial(*dynamic_cast<Commercial*>(properties[0]));.
In this example you could use static_cast<Commercial&>(*properties[0]) since you know properties[0] is a Commercial type.
However, in general if you're using dynamic_cast it probably means you're not sure what the derived type is and you would need to check for NULL (i.e., the cast failed) before dereferencing.
Alternative
You could consider a polymorphic API to take care of this for you.
class Base
{
public:
virtual ~Base() = default;
Base* clone() const = 0;
};
class D1 : public Base
{
public:
virtual ~D1() override = default;
D1* clone() const { return new D1(*this); }
};
class D2 : public Base
{
public:
virtual ~D2() override = default;
D2* clone() const { return new D2(*this); }
};
int main()
{
std::unique_ptr<Base> b1(new D2());
std::unique_ptr<Base> b2(b1->clone());
return 0;
}

It would be nice to see the errors but it looks like you aren't calling the copy constructor at all:
new Commercial(dynamic_cast<Commercial*>(properties[0]));
is like calling
Commercial(Commercial * other);
so you need
new Commercial(*dynamic_cast<Commercial*>(properties[0]));

Related

C++ implement class constructs instance of another classes depending on string it consumes

I need to implement one abstract class, three its concrete subclasses, class which goal to create one of this three classes instances and last class executor of three classes. Requirements are c++98, and not to use if/elseif/else to construct class instance, like i did in a Maker class method make Form. What mechanism i need to avoid if / elseif / else?
For example:
test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
class Executor {
private:
const std::string name;
public:
Executor(const std::string &name = "") {};
const std::string getname() const {return name;}
};
class BForm {
private:
const std::string _name;
public:
BForm(const std::string &name = "") : _name(name) {};
virtual ~BForm() {};
virtual void execute(const Executor &src) = 0;
const std::string getname() {return _name;}
virtual const std::string gettarget() = 0;
};
class Form1 : public BForm{
private:
std::string _target;
public:
Form1(const std::string &target = "") : BForm("form1"), _target(target) {};
virtual ~Form1() {};
virtual void execute(const Executor &src) {
std::cout << src.getname() << " exec form1 target:" << _target << std::endl;
}
virtual const std::string gettarget() {return _target;}
};
class Form2 : public BForm {
private:
std::string _target;
public:
Form2(const std::string &target = "") : BForm("form2"), _target(target) {};
virtual ~Form2() {};
virtual void execute(const Executor &src) {
std::cout << src.getname() << " exec form2 target:" << _target << std::endl;
};
virtual const std::string gettarget() {return _target;}
};
class Form3 : public BForm {
private:
std::string _target;
public:
Form3(const std::string &target = "") : BForm("form3"), _target(target) {};
virtual ~Form3() {};
virtual void execute(const Executor &src) {
std::cout << src.getname() << " exec form3 target:" << _target << std::endl;
};
virtual const std::string gettarget() {return _target;}
};
class Maker {
public:
BForm *makeForm(const std::string &name, const std::string &target)
{
/* need to avoid */
if (name == "form1")
return new Form1(target);
else if (name == "form2")
return new Form2(target);
else
return new Form3(target);
}
};
#endif
main.cpp
#include "test.h"
int main() {
Maker maker;
BForm *form;
Executor exec("executor");
form = maker.makeForm("form1", "A");
std::cout << form->getname() << " " << form->gettarget() << std::endl;
form->execute(exec);
delete form;
return (0);
}
You could typedef a pointer to function and then use a map from string to this type (pointer to function). And then use your parameter with indexer syntax to access the correct pointer to function.
Here is an example:
#include <iostream>
#include <map>
// The class definitions with a virtual function hello() common to all
class Base { public: virtual void hello() = 0; };
class Derived1 : public Base { public: void hello() { std::cout << "Derived1"; } };
class Derived2 : public Base { public: void hello() { std::cout << "Derived2"; } };
// The object making functions
Base* Maker1() { return new Derived1; }
Base* Maker2() { return new Derived2; }
int main()
{
// In C++98, without auto, it's worthwhile to typedef complicated types.
// The first one is a function type returning a pointer to Base...
typedef Base* MakerT();
// ... the second one is a map type projecting strings to such function pointers
typedef std::map<std::string, MakerT*> StrToMakerT;
/// The actual map projecting strings to maker function pointers
StrToMakerT strToMaker;
// Fill the map
strToMaker["D1"] = &Maker1;
strToMaker["D2"] = &Maker2;
// user input
std::string choice;
// as long as output works, input works, and the user didn't say "Q":
while (std::cout << "Please input 'D1' or 'D2' or 'Q' for quit: "
&& std::cin >> choice
&& choice != "Q")
{
// Prevent adding new entries to the map foir unknown strings
if (strToMaker.find(choice) != strToMaker.end())
{
// Simply look the function up again, the iterator type is too
// cumbersome to write in C++98
Base* b = (*strToMaker[choice])();
b->hello();
std::cout << '\n';
delete b;
}
else
{
std::cout << "Didn't find your choice, try again.\n";
}
}
std::cout << "Thank you, good bye\n";
}

C++ I have some seryous issues with inheritance when derived and base class have different types of parameters, like shown below:

Im a newbie in c++ and recently discovered classes;
I learned about constructors, overloading operators, the rule of three and right now i tried to learn inheritance.
I created 4 classes: 2 parents, 2 childs, but i occured some problems in class parent1
This is class parent1:
class parent1{
protected:
float slr;
int age;
char *name;
void set_new_name(char ch[10001]);
public:
parent1()
{
slr=0.0;
age=0;
name=NULL;
}
parent1(char ch[10001], float sl, int ag)
{
slr=sl;
age=ag;
set_new_name(ch);
}
parent1(const parent1 &p1)
{
char temp[10001];
strcpy(temp,p1.name);
if(name != NULL)
delete[] name;
set_new_name(temp);
slr=p1.slr;
age=p1.age;
}
parent1 &operator=(const parent1 &p1)
{
/// same lines as in copy constructor above
return *this;
}
char* get_name() const;
void print1();
~parent1()
{
delete[] name;
}
};
This is his child class, child1:
class child1 : public parent1{
protected:
int id;
void set_id(int j);
public:
child1(): parent1()
{
set_id(0);
}
child1(char ch[10001],float sl, int ag, int j): parent1(ch,sl,ag)
{
set_id(j);
}
child1(const child1 &p2): parent1(p2)
{
set_id(p2.get_id());
}
child1 &operator=(const child1 &p2)
{
set_id(p2.get_id());
parent1::operator=(p2);
}
int get_id() const;
void print2();
};
There is class parent 2:
class parent2{
protected:
char *name1;
char *name2;
void set_new_name1(char ch1[10001]);
void set_new_name2(char ch2[14]);
public:
parent2()
{
name1=NULL;
name2=NULL;
}
parent2(char ch1[10001], char ch2[14])
{
set_new_name1(ch1);
set_new_name2(ch2);
}
parent2(const parent2 &p3)
{
char temp2[10001];
strcpy(temp2,p3.name1);
if(name1 !=NULL)
delete[] name1;
set_new_name1(temp2);
/// .. . same lines as above, this time for name2 and p3.name2
}
parent2 &operator=(const parent2 &p3)
{
/// .. same lines as in copy constructor above
return *this;
}
char* get_name1() const;
char* get_name2() const;
void print3();
~parent2()
{
delete[] name1;
delete[] name2;
}
};
And there is his child, child 2:
class child2: public parent2{
protected:
char *job;
void set_new_job(char ch3[15]);
public:
child2(): parent2()
{
job=NULL;
}
child2(char ch1[10001], char ch2[10001],char ch3[11]): parent2(ch1,ch2)
{
set_new_job(ch3);
}
child2(const child2 &p4): parent2(p4)
{
char temp6[11];
strcpy(temp6, p4.job);
if(job != NULL)
delete[] job;
set_new_job(temp6);
}
child2 &operator=(const child2 &p4)
{
/// same lines as in copy constructor
parent2::operator=(p4);
}
char* get_job() const;
void print4();
~child2()
{
delete[] job;
}
};
As u can see up here, class parent1 have 3 types of parameters ( one float, one int and one char*).
Nonte: set_ functions works ok, get_functions just return class parametes (also works ok) , print functions just print classes parameters ( ex: cout << name1; also works fine)
The problem is that this code refuse to work when i create the objects in main.
First i thought it is operator= being overloaded to many times, bit it turned out to be the float parameter from parent1
There is the main:
char ch[10001]="my name", ch1[10001]="my name 1", ch2[14]="my name 2", ch3[11]="some code";
int ag=10;
float sl=10.1;
parent1 o1;
o1=parent1(ch,sl,ag);
o1.print1();
parent1 o2(o1);
o2.print1();
child1 o3;
o3=child1(ch,sl,ag,3);
o3.print2();
child1 o4;
o4=child1(ch,sl,ag,6);
o4.print2();
o4=o3;
o4.print2();
parent2 o5;
o5=parent2(ch1,ch2);
o5.print3();
child2 o6(ch1,ch2,ch3);
o6.print4();
The only things that seems to make it run are:
deleting the float parameter from parent1;
deleting the last class ; (i really don't know why the last class affect the program)
creating the last object like this : child2 o6(ch1,ch2,ch3); , which is frustrating because it should work like the others;
I know the code i sheared is very long, but Please , Help me to understand what i need to do to solve this stupid bug !
I see at least 3 issues in the code that will lead to a crash/undefined behavior.
First:
parent1(const parent1 &p1)
{
char temp[10001];
strcpy(temp,p1.name);
if(name != NULL) // name isn't initialized yet,
delete[] name; // these 2 lines shouldn't be here
set_new_name(temp);
slr=p1.slr;
age=p1.age;
}
Second: (these ones are reported by the compiler when warnings are enabled)
child1 &operator=(const child1 &p2)
{
set_id(p2.get_id());
parent1::operator=(p2);
return *this; // this line is missing
}
Third:
child2 &operator=(const child2 &p4)
{
char temp7[11];
strcpy(temp7, p4.job);
if(job != NULL)
delete[] job;
set_new_job(temp7);
parent2::operator=(p4);
return *this; // this line is missing
}
The return statement is not "inherited". Each function that's supposed to return something must do so.
With these changes the code runs:
my name
my name
3
6
3
my name 1
my name 2
some code
(Live demo)
Some additional improvement notes:
An array like char ch[10001] can't really be a function argument in C++. When it's used as an argument it silently decays to char *. So you might as well replace all char ch[10001] with const char* ch (and better yet, std::string), to avoid confusion.
Also, there's no point in allocating a temp array. You can just directly do set_new_name(p1.name):
parent1(const parent1 &p1)
{
set_new_name(p1.name);
slr=p1.slr;
age=p1.age;
}
It would be prudent to invest some time in getting familiar with a Debugger. It's all but impossible to make a working application without debugging it. And enable compiler warnings. With GCC use -Wall -Wextra, with MSVC - /W4.
Here's an example of the code using std::string. Thanks to std::string we can follow the rule of 0:
class parent1 {
protected:
float slr = 0;
int age = 0;
string name;
void set_new_name(string const &ch) { name = ch; }
public:
parent1() {}
parent1(string const &name, float slr, int age)
: slr(slr), age(age), name(name) {}
string const &get_name() const { return name; }
void print1();
};
void parent1::print1() { cout << get_name() << '\n'; }
class child1 : public parent1 {
protected:
int id = 0;
void set_id(int j) { id = j; }
public:
child1() : parent1() {}
child1(string const &name, float sl, int ag, int j)
: parent1(name, sl, ag), id(j) {}
int get_id() const { return id; }
void print2();
};
void child1::print2() { cout << get_id() << '\n'; }
class parent2 {
protected:
string name1;
string name2;
void set_new_name1(string const &ch) { name1 = ch; }
void set_new_name2(string const &ch) { name2 = ch; }
public:
parent2() {}
parent2(string const &name1, string const &name2)
: name1(name1), name2(name2) {}
string const &get_name1() const { return name1; }
string const &get_name2() const { return name2; }
void print3();
};
void parent2::print3() {
cout << get_name1() << '\n';
cout << get_name2() << '\n';
}
class child2 : public parent2 {
protected:
string job;
void set_new_job(string const &ch) { job = ch; }
public:
child2() : parent2() {}
child2(string const &name1, string const &name2, string const &job)
: parent2(name1, name2), job(job) {}
string const &get_job() const { return job; }
void print4();
};
void child2::print4() { cout << get_job() << '\n'; }
And this works equally well.

pure virtual function calling

The first printable(e) is giving "entity" but for the next line, the program crashes. giving some characters. Let me know the error.
#include<iostream>
using namespace std;
class A
{
public:
virtual string getclassname() = 0;
};
class entity : public A
{
public:
string getclassname() override
{
cout << "entity" << endl;
}
};
class player : public entity
{
private:
string m_name2;
public:
player(const string& name2) // Creating a constructor
:m_name2(name2) {}
string getname()
{
return m_name2;
}
public:
string getclassname() override
{
cout << "player" << endl;
}
};
void printable(A* en)
{
cout << en->getclassname() << endl;
}
int main()
{
entity* e = new entity();
player* p = new player("bird");
printable(e);
printable(p);
}
Your getclassname() function doesn't return anything even though it promises it does. This results in undefined behaviour. You should not print, but instead compose a string:
string getclassname() override
{
return "player";
}

Base Class Function Not Calling Derived Class Function

I've looked around at multiple questions on this topic on SO as well as several references and have not seen this issue come up anywhere.
When my instance of Derived calls Base::GetValue() (which calls the virtual doGetValue(), defined in Derived and in Base), Base::doGetValue() is called instead of Derived::doGetValue(). Why is that and what do I need to do differently?
Is it because Derived::doGetValue() is private instead of protected? That seems to me to be the most likely explanation, but I haven't seen that explicitly stated anywhere that I've looked so far.
Here is my code on coliru.
Below is my code:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
using namespace std;
class Base
{
private:
virtual string doGetname( ) const { return "Base"; };
protected:
virtual void doGetValue( map<string,string> &ds, const bool include ) const;
inline void doGetValue( map<string,string> &ds ) const { doGetValue(ds, true); };
public:
string GetValue( ) const;
string GetName( ) const { return doGetname(); };
};
class Derived : public Base
{
private:
virtual void doGetValue( map<string,string> &ds ) const;
virtual string doGetname( ) const { return "Derived"; };
};
struct generate_value_from_map : std::unary_function<void, void>
{
generate_value_from_map( string *_val, const string assignment = " " ):val(_val)
{
count = 0;
insert = (*_val);
first = "(";
second = ") "+assignment+" (";
}
void operator() (pair<const string,string> &i)
{
first += ( count > 0 ? "," : "" ) + i.first;
second += ( count > 0 ? "," : "" ) + i.second;
(*val) = insert + first + second + ")";
++count;
}
private:
int count;
string *val;
string insert;
string first;
string second;
};
string Base::GetValue( ) const
{
string ret_val = "name is: " + GetName() + " \n";
map<string,string> ret_map;
this->doGetValue(ret_map);
for_each(ret_map.begin(), ret_map.end(), generate_value_from_map(&ret_val));
return ret_val;
}
void Base::doGetValue( map<string,string> &ds, const bool include ) const
{
//base implementation
//fills ds with values from Base
ds["type"] = "Base";
ds["id"] = "Id";
}
void Derived::doGetValue( map<string,string> &ds ) const
{
Base::doGetValue( ds );
//derived implementation
//fills ds with values from Derived
ds["type"] = "Derived";
ds["name"] = "Name";
}
int main()
{
shared_ptr<Derived> obj ( new Derived() );
string val = obj->GetValue();
cout << val;
//do stuff with val
}
I tried to include all the specifics of my issue, excluding some of the delphi-inherited features of my compiler (RAD Studio XE4).
The definitions of doGetValue are different between base and derived.
Base:
virtual void doGetValue( map<string,string> &ds, const bool include ) const;
inline void doGetValue( map<string,string> &ds ) const { doGetValue(ds, true); };
Derived:
virtual void doGetValue( map<string,string> &ds ) const;
In the base the function is not virtual.

inheritance and memcpy - How is it work together?

I have this code:
#include <iostream>
#include <string>
#include <cstring>
class Animal
{
public:
Animal(const std::string &name) : _name(name)
{
}
virtual void Print() const = 0;
virtual ~Animal() {}
protected:
std::string _name;
};
class Dog : public Animal
{
public:
Dog(const std::string &name, const std::string &dogtype) : Animal(name), _dogtype(dogtype)
{
Print();
}
void Print() const
{
std::cout << _name << " of type " << _dogtype << std::endl;
}
private:
std::string _dogtype;
};
class Cat : public Animal
{
public:
Cat(const std::string &name, int weight) : Animal(name), _weight(weight)
{
Print();
}
virtual void Print() const
{
std::cout << _name << " of weight " << _weight << std::endl;
}
virtual ~Cat(){}
private:
int _weight;
};
class Tiger : public Cat
{
public:
Tiger(const std::string &name, int weight, double speed) : Cat(name, weight), _speed(speed)
{
Print();
}
void Print() const
{
std::cout << _name << " speed " << _speed << std::endl;
}
virtual ~Tiger(){std::cout << "Tiger's dtor" << std::endl;}
private:
int _speed;
};
int main()
{
Animal *a = new Tiger("theRealKing", 3, 40.5);
Cat *c = new Cat("silvester", 4);
memcpy(c, a, sizeof(Cat));
c->Print(); /// ------------------------
delete a;
delete c;
return 0;
}
in the line : c->Print():
the line before that c became a tiger so why does it print me this line :
Ross with speed 135081
insted of
Ross with speed 3
why there is a memory problem ?
why does it call the print method of tiger and not of cat ?
It doesn't work together.
Using memcpy on these objects produces undefined behavior, the Standard permits anything to happen.
It isn't inheritance per se that is causing you problems, but the presence of virtual member functions or custom constructor/destructor. These make your objects lose the trivially-copyable classification that is required when using memcpy.
Your class isn't trivially-copyable for a second reason -- it contains a member of type std::string which is not trivially-copyable.
In practical terms, when you perform a bitwise copy of a std::string subobject, you end up with two pointers to the same memory, and both string objects will try to free this pointer. That will crash your program. If using memcpy on a v-table hasn't done so earlier.
But when you mix in optimizations, even weirder things can happen. That's what undefined behavior means.
You should avoid using memcpy for objects in c++, use the copy constructor instead.