0

I am trying to run the following C++ code to understand class inheritance using MS Visual Studio 15. After I build and run the code, I get a message saying MS VS has stopped working. I'd really appreciate if someone can help me understand what I am doing wrong.

#include<cstdio>
#include<string>
#include<conio.h>
using namespace std;

// BASE CLASS
class Animal {
private:
    string _name;
    string _type;
    string _sound;
    Animal() {};     
protected: 
    Animal(const string &n, const string &t, const string &s) :_name(n), _type(t), _sound(s) {};    
public: 
    void speak() const;     
};

void Animal::speak() const {
    printf("%s, the %s says %s.\n", _name, _type, _sound);
}

// DERIVED CLASSES 
class Dog :public Animal { 
private:
    int walked;
public:
    Dog(const string &n) :Animal(n, "dog", "woof"), walked(0) {};
    int walk() { return ++walked; }
};


int main(int argc, char ** argv) {    
    Dog d("Jimmy"); 
    d.speak();          
    printf("The dog has been walked %d time(s) today.\n", d.walk());        
    return 0;
    _getch();
}

3 Answers3

1
printf("%s, the %s says %s.\n", _name, _type, _sound);

You cannot use std::string with printf() that way.

Use

printf("%s, the %s says %s.\n", _name.c_str(), _type.c_str(), _sound.c_str());

instead.


I'd rather recommend to use std::cout to get everything seamlessly working in c++.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

The problem is that the speak method tries to use printf in order to print a string object.

The printf function is not suitable for printing std::string objects. It does works on char arrays, which are used for representing strings in the C language. If you want to use printf anyway, you'll need convert your strings into char arrays. This can be done as follows:

printf("%s, the %s says %s.\n", _name.c_str(), _type.c_str(), _sound.c_str());

A more elegant solution, will be to print the data in the "C++" way, by using std::cout:

//include declaration at the top of the document
#include <iostream>
...
//outputs the result
cout <<_name + ", the " + _type + " says " + _sound << "." << endl;
Community
  • 1
  • 1
ibezito
  • 5,782
  • 2
  • 22
  • 46
0

printf with %s expects a c-style null-terminated byte string, not std::string, they're not the same thing. So printf("%s, the %s says %s.\n", _name, _type, _sound); won't work, it shouldn't compile.

You can use std::string::c_str(), which will return a const char*. Such as

printf("%s, the %s says %s.\n", _name.c_str(), _type.c_str(), _sound.c_str());

Or use std::cout with std::string like:

cout << _name << ", the " << _type << " says " << _sound << ".\n";
songyuanyao
  • 169,198
  • 16
  • 310
  • 405