I am familiar with creating classes and using dot notations to access functions for the objects. I am unfamiliar with the notation of doing the same but with pointers. Please take a look at my code and suggest how I change the code in the class definition, not main.
main:
Pet * p = new Pet( "Sunset", "Cat", "meow..." );
cout << "The " << p->getVariety( ) << " " << p->getName( ) << " speaks by saying " << p->spea( ) << endl;
class:
class Pet
{
public:
Pet( );
Pet( std::string name, std::string variety, std::string says )
{
using namespace std;
myName = name;
myVariety = variety;
howIspeak = says;
}
std::string getName( ) const
{
return myName;
};
std::string getVariety( ) const
{
return myVariety;
};
virtual void speak( );
protected:
std::string myName;
std::string myVariety;
std::string howIspeak;
};
I would suggest reading an introductory book on C++, "C++ Primer (4th Edition)" by Lippmann et al. or finding an on-line tutorial on C++. The problem you are solving requires more understanding than can be related in an SO Q and A.
The
using namespace std;
is useless in there, just remove it.Then, you are having
virtual
methods andprotected
members, which suggests that you are willing to inherit from that class: either don't or define avirtual
destructor as well.Also, the
speak
member function you are calling from the main, returnsvoid
, which is not a type you want to pass tooperator<<
ofstd::cout
.And finally: why are you using nake pointers and dynamic allocation? Don't use it unless you are absolutely forced to, and even then, use
std::shared_ptr
orstd::unique_ptr
(or any other of the smart pointers family) instead:After that line,
ptr
will behave almost like any other pointer, except it will clean himself up (will calldelete
) when you are done with it (when it leaves the scope).I guess, it's the
in
which causes the error message. You cannot output a
void
value tostd::ostream
.Presumably, it should have been