this is a similar example to what i have. it's simplified but it still get's the same error.

i need to be able to use << operator to print out all information from class A. i have no idea how to do that. i tried casting it as an A object but then it starts telling me that i can do that with virtual functions. is there any way to go around this?

#include <iostream>
#include <string>
using namespace std;

class A {
public:
	string name;
	A(string sName) {
		name = sName;
	}
	virtual void mission();
	string getName() {
		return name;
	}
	friend ostream& operator << (ostream& out, A& oA) {
		out << oA.getName() << endl;
		return out;
	}
};

class B : public A {
public:
	B() : A("bob") {
		name = "bob";
	}
};

int main() {

	B DUDE;

	cout << DUDE;
        // this doesnt work either
        cout << (A)DUDE;

	return 0;
}

Recommended Answers

All 3 Replies

comment out

virtual void mission();

and try

and give different names for base class and derived class 'name' variable to see the difference.

What's a problem?

class A {
public:
    A() {}
    explicit A(const std::string& n):name(n) {}
    const std::string& getName() const {
        return name;
    }
protected:
    std::string name;
};

inline
std::ostream& operator<<(std::ostream& os,const A& a) {
    os << a.getName();
    return os;
}

class B: public A {
public:
    B():A() {}
    explicit B(const std::string& n):A(n) {}
};

inline 
std::ostream& operator<<(std::ostream& os,const B& b) {
    return operator<<(os,static_cast<const A&>(b));
};

void abtest()
{
    B dude("mbayabo");
    std::cout << dude << std::endl;
}

mayabo's original code (other than the line cout << (A)DUDE; ) should actually work. The line name="bob"; in B's constructor is not required (and A::name can be made private).

The compiler is able to do the conversion "derived class to public base" (i.e. B to A) implicitly.

If you're getting errors, then either there is some code in play not being shown or you have a buggy compiler (really old versions of VC++ come to mind).

It would probably be better to make getName() a const method (optionally virtual) and for the operator<<() to have its second argument a const reference.

And "using namespace std;" before a class definition: wash your mouth out with soap, particularly if you do that in a header file.....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.