Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Virtual print functions overriding << operator: I\'ve been having a lot of probl

ID: 3768581 • Letter: V

Question

Virtual print functions overriding << operator: I've been having a lot of problems with this assignment it is to create a virtual print function for the base class gun that other classes inherit from.

gun.h

gun.cpp

handgun.h

handgun.cpp

pistol.h

#ifndef CH14_PISTOL_H

#define CH14_PISTOL_H

#ifndef PISTOL_H

#define PISTOL_H

#include <string>

using std::string;

#include "handgun.h"

namespace guns{

class Pistol : public Handgun{

public:

Pistol();

Pistol(const string& theManufacturer, const string& theCaliber, const string& theGrips, const string& theSights, bool theLaser, bool theSemiauto);

bool getSemiauto() const;

void setSemiauto(bool theSemiauto);

string printSemiauto();

void print();

private:

bool semiauto;

};

}

#endif //PISTOL_H

pistol.cpp

revolver.h

revolver.cpp

#endif //CH14_PISTOL_H

please read:

https://www.chegg.com/homework-help/questions-and-answers/ve-stuck-week-half--keep-getting-46-error-void-guns-gun-operator-q9489601

I posted this question before and got an answer, I'm just looking for it to be expanded on. I've tried multiple resources for research and just need someone to help make it click. I find that while sometimes code seems to come to me, I get caught up on certain details that can set me back weeks.

Explanation / Answer

The problem here is that the operator << is a free function which can't be virtual. Now to make it virtual we can do this

In gun class declaration is correct.

It should be

virtual void print(ostream& where) const;

Now the problem is in gun.cpp where we are overidding << operator. The correct code should be:

ostream& operator<< (ostream& out, const gun& mygun) {
    mygun.print(out);
    return out;
}

Here we need to call our virtual function and then overide the << operator in c++. With this now we can use this operator. the above code should be replaced with the same function present in gun.cpp