How can I call base class's operator==? - c++

My problem is just i dont know what to paste where i writed HELP_HERE(see the code above class Dog in function bool operator==) in order to get he comparation between the type Animal of two Dogs. Each dog is an Animal so i need to be able to return the variable that represents "the animal inside the dog". In java i could just use super() and it works what do i need in c++?
`
#include "Animal.h"
class Dog : public Animal
{
private:
char _name;
int _age;
int _hps;
float _peso; // peso is Weight
public:
Dog(char name,int age, float peso, int hps) : Animal(name,age),_peso(peso),_hps(hps) {}
void roar(std::ostream &os) const {
os << "O cao " << _name << " esta a ladrar\n.";
}
int Vidas() const {
return _hps;
}
float Peso() const {
return _peso;
}
int returnAnimal() {
return animal.Age();
}
bool operator==(const Dog &dog) {
return HELP_HERE.operator==(dog.HELP_HERE) &&
dog.Vidas() == _hps && dog.Peso() == _peso;
}
friend std::ostream &operator<<(std::ostream &os, const Dog &dog) {
dog.roar(os);
return os;
}
};`
Class Animal:
#ifndef ANIMAL_H
#define ANIMAL_H
#include <iostream>
class Animal {
int _age;
char _name;
public:
Animal(int age) : _age(age),_name('-') {}
Animal(int age, char name) : _age(age), _name(name) {}
int Age() const { return _age; }
char Name() const { return _name; }
friend std::ostream &operator<<(std::ostream &os, const Animal &animal) {
animal.sleep(os);
return os;
}
void sleep(std::ostream &os) const {
os << "the animal " << Name() << " is sleeping.\n";
}
void Age(int age) { _age = age; }
bool operator==(const Animal &animal) {
return _age == animal.Age() && _name == animal.Name();
}
};
#endif // ANIMAL_H

Change HELP_HERE.operator==(dog.HELP_HERE) to:
Animal::operator==(dog)
In general you can get an Animal reference with: Animal &a = *this; . C++ doesn't have a keyword which indicates "the parent class", however you can always make your child class contain typedef Animal super; and then you can use super::operator==, or super &a = *this; etc.

Related

How should i overload += operator in a vector template?

I got a template class Atlas that will store objects of Animal class and derived classes of Animal;
here's the code:
#include <iostream>
#include <assert.h>
#include <list>
using namespace std;
class Animal {
protected:
std::string m_name;
Animal (std::string name): m_name {name} {}
public:
virtual std::string regn() const { return "???"; }
virtual ~Animal(){
cout << "Destructor animal"<<'\n';}
};
class Nevertebrate : public Animal{
public:
virtual std::string regn() const { return "nevertebrate";}
virtual ~Nevertebrate();
};
class Vertebrate: public Animal {
protected:
/* std::string m_name;
Vertebrate (std::string name)
:m_name {name} {} */
Vertebrate (std::string name)
: Animal {name} {}
public:
virtual std::string regn() const { return "vertebrate";}
virtual ~Vertebrate(){
cout<<"Destructor vertebrate"<<'\n';};
};
class bird: public Vertebrate {
public:
bird(std::string name)
: Vertebrate{ name }{}
void set_name (std::string nume){
m_name = nume;}
std::string get_name(){
return m_name;}
virtual std::string regn() const {return "pasare";}
virtual ~bird (){
cout << "destructor bird"<<'\n';}
};
template <class T>
class Atlas
{
private:
int m_length{};
T* m_data{};
public:
void SetLength(int j);
Atlas(int length)
{
assert(length > 0);
m_data = new T[length]{};
m_length = length;
}
Atlas(const Atlas&) = delete;
Atlas& operator=(const Atlas&) = delete;
~Atlas()
{
delete[] m_data;
}
void erase()
{
delete[] m_data;
m_data = nullptr;
m_length = 0;
}
T& operator[](int index)
{
assert(index >= 0 && index < m_length);
return m_data[index];
}
int getLength() const;
};
template <class T>
int Atlas<T>::getLength() const
{
return m_length;
}
template <class T>
void Atlas<T>::SetLength(int j){m_length = j;
}
int main()
{
Atlas<Bird> AtlasBird(10);
Bird b;
AtlasBird.SetLength(11);
AtlasBird[10] = b --- it gets a memoryleak from here.
return 0;
}
I want to overload the += operator so that i can insert a new object into my Atlas, (e.g. AtlasAnimal).
I tried with the SetLength function to increase the length, (e.g. AtlasAnimal.SetLength(11)) but when i try to assign AtlasAnimal[10] an object (e.g. Bird b) it drops a memory leak.
I'm sorry if there was a similar question answered, but i couldn't find anything that helps

Overload += for a template?

I have a base class Animal and a derived class Bird : Animal. I use a template class that will store vectors of pointers to either Animal or Bird objects. I want to overload the += operator in such a way that I can insert a new animal right in the Atlas, so m_length = m_length + 1, pages.push_back(animal), just to get the idea.
Here's my template class:
template <class T>
class Atlas2 {
public:
int m_length;
std::list<T> pages;
Atlas2() { m_length = 0; }
~Atlas2() {}
void adauga(T data);
T operator+=(const T& data) {
this->m_length++;
this->pages.push_back(data);
return *this;
};
};
And here's the Animal/Bird classes:
class Animal {
protected:
std::string m_name;
public:
Animal() {}
Animal(std::string name) : m_name{name} {}
virtual void set_name(std::string name) { m_name = name; }
virtual std::string get_name() { return m_name; }
virtual std::string regn() const { return "???"; }
virtual ~Animal() { cout << "Destructor animal" << '\n'; }
};
class Bird : public Animal {
public:
bird() : animal() {}
bird(std::string name) : Animal{name} {}
void set_name(std::string nume) { m_name = nume; }
std::string get_name() { return m_name; }
std::string regn() const override { return "pasare"; }
~bird() { cout << "destructor pasare" << '\n'; }
};
However, I can't figure this out. When I use the overloaded += operator in main() like this:
Pasare *c = new Pasare{"vulture"};
Atlas2<Animal *> Atlas;
Atlas += c;
It shows me an error, that it couldn't convert Atlas<Animal *> to <Animal*>.
How should I implement this correctly? Any tip?
Note: The template works fine, I can store in my list pointers to either Animal or Birds without problems, and access their specific methods. I just can't figure out the += part.
You should return Atlas2<T> & not T:
Atlas2<T>& operator+=(const T& data) {
this->m_length++;
this->pagini.push_back(data);
return *this;
};
The basic problem is that you've declared your operator+= as returning a T, but the return statement in it is return *this;, which is an Atlas2<T>.
If you change the return type to Atlas2<T> &, it should work. That's what you would normally want to return from an operator+= anyways, though with your use, it doesn't matter much as you're ignoring the returned value.

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.

C++ - Printing vector<base*> elements for derived class objects

I have an abstract class named Pet and three derived classes Cat Dog Goldfish. I am trying to store them in vector and print the pets names. But I am getting some hexadecimal number. I don't know where I am doing wrong.
// Here is pet.h
#ifndef PET_H
#define PET_H
#include<iostream>
using namespace std;
class Pet
{
public:
//constructor
Pet(string);
// virtual destructor
virtual ~Pet();
// pure virtual function
virtual string speak() = 0;
//getters setters
string getName();
//overloading comparative operators
bool operator< (Pet&);
friend ostream& operator<<(ostream&, Pet&);
protected:
string pet_name; //name of pet
};
#endif // PET_H
Here is pet.cpp
#include <iostream>
#include "Pet.hpp"
#include <string>
using namespace std;
//constructor
Pet::Pet(string name) : pet_name(name)
{}
//overloading comparator function
bool Pet::operator<(Pet& obj)
{
return ((pet_name.compare(obj.pet_name)) < 0);
}
//getter for name
string Pet::getName() { return pet_name; }
// destructor
Pet::~Pet() { /* dtor */ }
ostream& operator<<(ostream& output, Pet& p) {
output << "I am pet";
return output;
}
#ifndef CAT_H
#define CAT_H
#include "Pet.hpp"
class Cat: public Pet
{
public:
Cat(string);
virtual ~Cat();
string speak();
friend ostream& operator<<(ostream &, Cat&);
};
#endif // CAT_H
#include "Cat.hpp"
#include<string>
Cat::Cat(string name):Pet(name)
{
//ctor
}
string Cat::speak()
{
return ">>Meow Meow>>";
}
Cat::~Cat()
{
//dtor
}
ostream& operator<<(ostream& output, Cat& p) {
output << "I am " << p.getName() << " " << p.speak() << endl;
return output;
}
List.hpp File
#ifndef LIST_H
#define LIST_H
#include<iostream>
#include <vector>
#include<algorithm>
using namespace std;
template<class T>
class List
{
public:
void add_item(T);
void sortList();
void print();
private:
vector<T> list;
};
template<class T>
void List<T>::add_item(T item_list) {
list.push_back(item_list);
}
template<class T>
void List<T>::sortList() {
sort(list.begin(), list.end());
}
template<class T>
void List<T>::print() {
std::vector<T>::iterator i;
for (i = list.begin(); i != list.end(); ++i) {
cout << *i << endl;
}
}
#endif // LIST_H
And this is the main function
int main()
{
List<Pet*> pets;
// book items adding in the lists
pets.add_item(new Cat("Kitty"));
pets.add_item(new Cat("Tom"));
// sorting lists
pets.sortList();
// printing lists
// ----- Here is the PROBLEM ------
pets.print(); // --> Here I am getting problem
// --> when this statement executes, I get the hexa decimal number
// saving in files
return 0;
}
ftfy:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <memory>
class Pet
{
public:
Pet(std::string name) : name{ std::move(name) } {}
virtual ~Pet() = default;
std::string get_name() const { return name; }
virtual std::string speak() const = 0;
friend std::ostream& operator<<(std::ostream& output, Pet const &pet)
{
output << "I am pet named " << pet.name;
return output;
}
protected:
std::string name;
};
class Cat : public Pet
{
public:
Cat(std::string name) : Pet{ std::move(name) } {};
virtual ~Cat() = default;
virtual std::string speak() const override { return ">>Meow Meow>>"; }
friend std::ostream& operator<<(std::ostream &output, Cat const & cat)
{
output << "I am a cat named " << cat.name << ' ' << cat.speak();
return output;
}
};
class Dog : public Pet
{
public:
Dog(std::string name) : Pet{ std::move(name) } {};
virtual ~Dog() = default;
virtual std::string speak() const override { return ">>Woof Woof>>"; }
friend std::ostream& operator<<(std::ostream &output, Dog const & dog)
{
output << "I am a dog named " << dog.name << ' ' << dog.speak();
return output;
}
};
template<class T>
class List
{
public:
void add_item(T item_list) { list.push_back(item_list); }
void sortList() {
std::sort(list.begin(), list.end(),
[](T const &lhs, T const &rhs) -> bool { return lhs.get()->get_name() < rhs.get()->get_name(); });
}
void print() const
{
for (typename std::vector<T>::const_iterator i{ list.begin() }; i != list.end(); ++i) {
if (auto cat = dynamic_cast<Cat*>((*i).get()); cat)
std::cout << *cat;
else if (auto dog = dynamic_cast<Dog*>((*i).get()); dog)
std::cout << *dog;
else
std::cout << **i;
std::cout.put('\n');
}
}
private:
std::vector<T> list;
};
int main()
{
List<std::shared_ptr<Pet>> pets;
pets.add_item(std::make_shared<Cat>("Kitty"));
pets.add_item(std::make_shared<Cat>("Tom"));
pets.add_item(std::make_shared<Dog>("Suzy"));
pets.add_item(std::make_shared<Dog>("Hasso"));
pets.sortList();
pets.print();
}

How to create a specialized and default versions of a function that take base and derived classes?

I have the following class architecture:
class Animal
{
// ...
}
class Cat : public Animal
{
// ...
}
class Dog : public Animal
{
// ...
}
// + Several other derived classes
In another section of my code, I have a function that goes through a list of Animals and needs to perform specialized actions in the case of several of the derived classes and a default action otherwise. How can I handle this situation elegantly, given the following constraints:
I'd like to keep the new code outside of Animal and its derived
classes because of separation of concerns.
I'd like to avoid using a switch statement on types or enums as it feels very smelly.
Here's one way - use the concept-model idiom (my name):
#include <iostream>
#include <vector>
struct AnimalConcept {
virtual ~AnimalConcept() = default;
virtual void make_noise() const = 0;
};
// default case
void make_noise_for(const AnimalConcept&)
{
std::cout << "no noise" << std::endl;
}
template<class Model>
struct AnimalModel : AnimalConcept
{
void make_noise() const override {
make_noise_for(static_cast<const Model&>(*this));
}
};
// some models
struct Cat : AnimalModel<Cat>
{
};
struct Dog : AnimalModel<Dog>
{
};
struct Giraffe : AnimalModel<Giraffe>
{
};
// separation of concerns - specific overrides
void make_noise_for(const Cat&) {
std::cout << "meow\n";
}
void make_noise_for(const Dog&) {
std::cout << "woof\n";
}
// test
using namespace std;
int main(){
std::vector<std::unique_ptr<const AnimalConcept>> animals;
animals.emplace_back(new Cat);
animals.emplace_back(new Dog);
animals.emplace_back(new Giraffe);
for (const auto& p : animals) {
p->make_noise();
}
return 0;
}
expected output:
meow
woof
no noise
And here's another way to implement it (this one is nicer since it allows all animals to have unrelated interfaces):
#include <iostream>
#include <vector>
struct AnimalConcept {
virtual ~AnimalConcept() = default;
virtual void make_noise() const = 0;
};
// default case
template<class T>
void make_noise_for(const T&)
{
std::cout << "this animal makes no noise" << std::endl;
}
template<class Model>
struct AnimalModel : AnimalConcept
{
template<class...Args>
AnimalModel(Args&&...args)
: _model { std::forward<Args>(args)... }
{}
private:
void make_noise() const override {
make_noise_for(_model);
}
Model _model;
};
// some models
struct Cat
{
Cat(std::string name)
: _name { std::move(name) }
{}
const std::string& name() const {
return _name;
}
private:
std::string _name;
};
struct Dog
{
Dog(std::string name, int age)
: _name { std::move(name) }
, _age { age }
{}
const std::string& name() const {
return _name;
}
int age() const {
return _age;
}
private:
std::string _name;
int _age;
};
struct Giraffe
{
};
// separation of concerns - specific overrides
void make_noise_for(const Cat& c) {
std::cout << c.name() << " says meow\n";
}
void make_noise_for(const Dog& d) {
std::cout << "the dog called " << d.name() << " who is " << d.age() << " years old says woof\n";
}
// test
using namespace std;
int main(){
std::vector<std::unique_ptr<const AnimalConcept>> animals;
animals.emplace_back(new AnimalModel<Cat> { "felix" });
animals.emplace_back(new AnimalModel<Dog> { "fido", 2 });
animals.emplace_back(new AnimalModel<Giraffe>);
for (const auto& p : animals) {
p->make_noise();
}
return 0;
}
expected output:
felix says meow
the dog called fido who is 2 years old says woof
this animal makes no noise
You can use a combination of the following to get type based dispatch.
Provide for every class to return a type ID associated with it.
Provide a virtual function in the base class to get the type ID associated with an object.
Provide a way for registration of functions based on type ID.
When the time comes for execution of the top level function, search for a registered function given an animal's type ID. If a function is registered, call it. Otherwise, use the default function.
// Implement this function in a .cpp file.
int getNextTypeID()
{
static int typeID = 0;
return ++typeID;
}
class Animal
{
virtual int getTypeID();
};
class Cat : public Animal
{
static int getID()
{
static int typeID = getNextTypeID();
}
virtual int getTypeID()
{
return getID();
}
};
class Dog : public Animal
{
static int getID()
{
static int typeID = getNextTypeID();
}
virtual int getTypeID()
{
return getID();
}
};
foo.h:
typedef void (*AnimalFunction)(Animal& a);
int registerAnimalFunctor(int typeID, AnimalFunction f);
void foo(Animal& a);
foo.cpp:
typedef std::map<int, AnimalFunction> AnimalFunctionMap;
AnimalFunctionMap& getAnimalFunctionMap()
{
static AnimalFunctionMap theMap;
return theMap;
}
int registerAnimalFunctor(int typeID, AnimalFunction f)
{
getAnimalFunctionMap()[typeID] = f;
return 0;
}
void defaultAnimalFunction(a)
{
// Default action
}
void foo(Animal& a)
{
AnimalFunctionMap& theMap = getAnimalFunctionMap();
AnimalFunctionMap::iterator iter = theMap.find(a.getTypeID());
if ( iter != theMap.end() )
{
iter->second(a);
}
else
{
defaultAnimalFunction(a);
}
}
cat_foo.cpp:
void CatFunction(Animal& a)
{
// Cat action.
}
int dummy = registerAnimalFunctor(Cat::getID(), CatFunction);
dog_foo.cpp:
void DogFunction(Animal& a)
{
// Dog action.
}
int dummy = registerAnimalFunctor(Dog::getID(), DogFunction);