0

I'm trying to make a program which saves in an object, all names got from another object, for example I have class Cheltuieli which saves a char and I have class Repo which saves an array with chars from Cheltuieli

I've tried changing cout << *c; with cout << *c->getName(); and I only get 1 letter: p instead of ["pizza", "pizza"]

Mancare.hpp

#ifndef Mancare_hpp
#define Mancare_hpp

class Cheltuieli{
private:
    char* name;
public:
    Cheltuieli();
    Cheltuieli(char* n);
    ~Cheltuieli();
    void setName(char* n);
    char* getName();
};

#endif

Mancare.cpp

#include "Mancare.hpp"
#include <string.h>

Cheltuieli::Cheltuieli()
{
    this -> name = NULL;
}
Cheltuieli::Cheltuieli(char* n)
{
    this -> name = new char[strlen(n) + 1];
    strcpy(this -> name, n);
}

Cheltuieli::~Cheltuieli()
{
    if(this -> name != NULL)
    {
        delete[] this -> name;
        this -> name = NULL;
    }
}

void Cheltuieli::setName(char *n)
{
    if(this -> name)
        delete[] this -> name;
    this -> name = new char[strlen(n) + 1];
    strcpy(this -> name, n);
}

char *Cheltuieli::getName()
{
    return this -> name;
}

void Repo::addElement(Cheltuieli &c)
{
    this -> cheltuieli[this -> size] = c;
    this -> size++;
}

Cheltuieli* Repo::getAll()
{
    return this -> cheltuieli;
}
char* const ps = "pizza";
Cheltuieli a = Cheltuieli(ps);

Repo n = Repo();
n.addElement(a);
n.addElement(a);

Cheltuieli* c = n.getAll();
cout << *c;

I get the output: 0x100503b38 with error Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream') and 'Cheltuieli')

Thank you!

2 Answers2

0

Try overloading << operator in Cheltuieli:

    friend ostream& operator<<(ostream& os, const Cheltuieli& x)
    {
        os << x.name;
        return os;
    }
Theodor Badea
  • 465
  • 2
  • 9
0

From what I can tell, the Cheltuieli class is implementing a very small subset of what's already done in the std::string class - but it's incomplete, so if you do:

Cheltuieli orig("something");
Cheltuieli cpy = orig;

both orig and cpy will have a name member pointing at the same address because of the default copy constructor. Read about The rule of three/five/zero.

Similarly, the Repo class seems to be implementing something close to a std::vector. I suggest that you don't start fiddling about with raw pointers but to use the standard classes for this. You could even make aliases for them:

using Cheltuieli = std::string;
using Repo = std::vector<Cheltuieli>;

Used like this:

Cheltuieli a = "pizza";
Repo n;
n.push_back(a);
n.push_back(a);

for(auto& cheltuieli : n) {
    std::cout << cheltuieli << "\n";
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108