-2

Am practicing C++ basic inheritance concepts, came across the need to print out a custom class object and wrote an overload, followed guide exactly yet still does not register use of the new operator for printing (<<).

Am wondering if typed incorrectly or had some declaration/initiation errors somewhere else?

no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘Choco’) std::cout<< "Choco value: " << child << endl;

#include <iostream>
using namespace std;

class Sweets {
        public:
                // pure virtual, child MUST implement or become abstract
                // Enclosing class becomes automatically abstract - CANNOT instantiate
                virtual bool eat() = 0;
};

// public inheritance : public -> public, protected -> protected, private only accessible thru pub/pro members
class Choco : public Sweets {
        public:

                bool full;

                Choco() {
                        full = false;
                }

                // Must implement ALL inherited pure virtual
                bool eat() {
                        full = true;
                }

                // Overload print operator
                bool operator<<(const Choco& c) {
                        return this->full;
                }
};

int main() {

// Base class object
//sweets parent;
Choco child;

// Base class Ptr
// Ptr value = address of another variable
Sweets* ptr; // pointer to sweets
ptr = &child;

std::cout<< "Sweets* value:  " << ptr << endl;
std::cout<< "Choco address: " << &child << endl;
std::cout<< "Choco value: " << child << endl; // Printing causes error!
}
Kerberos
  • 4,036
  • 3
  • 36
  • 55
jamarcus_13
  • 55
  • 2
  • 10
  • Related: https://stackoverflow.com/q/4421706/1896169 – Justin Nov 08 '17 at 20:44
  • 1
    Related: https://stackoverflow.com/questions/476272/how-to-properly-overload-the-operator-for-an-ostream – Guillaume Racicot Nov 08 '17 at 20:45
  • @jamarcus_13 This operator bool operator<<(const Choco& c) { return this->full; } does not make sense at least because the parameter c is not used.:) – Vlad from Moscow Nov 08 '17 at 20:47
  • This doesn't address the question, but the logic of this class is inside-out. If a person eats the chocolate, it's the **person** who becomes full, not the **chocolate**. – Pete Becker Nov 08 '17 at 21:43

1 Answers1

0

The operator is defined the following way outside the class because it is not a class member.

std::ostream & operator <<( std::ostream &os, const Choco &c ) 
{
    return os << c.full;
}

Take into account that the function

bool eat() {
    full = true;
}

shall have a return statement with an expression of the type bool or it should be declared with the return type void in the base and derived classes.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335