-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
  • 3,796
  • 3
  • 34
  • 54
jamarcus_13
  • 55
  • 2
  • 9

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
  • 265,791
  • 20
  • 170
  • 303