Complete the class "Musician" to produce the following output:
Name = PK. Genre = Jazz
Name = LG. Genre = Pop

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

class Human {
  string name;
  Human (string name) : name(name) { }
  string getName() { return name; }

class Musician : public Human {
  string genre;
  Musician (string name, string genre) : Human(name), genre(genre){}
  void print() const


        cout<<"Name = "<< getName()<<" Genre = "<<genre << endl;


int main() {
  Musician m1("PK", "Jazz");
  Musician* m2 = new Musician ("LG", "Pop");
  delete m2;

i have error at the print function..
how to print out the getName..
what is the use void print () const with void print ()???



You have a function called print() which promises to not change an object due to its "const" qualifier. Within that function, it calls a function called getName() which DOES NOT make that promise. So can print() truly make good on its promise to not change anything? No.

Think of it this way. I give my brother the keys to my house so he can watch it while I'm on vacation, extracting the promise that he won't do anything dumb to damage it. He swears up and down that he won't do anything, then gets called away on business and sub-contracts the job to his eleven year old son. He can't really make good on his promise that the house will be fine. If I had wanted to entrust an eleven year old with my house, I would have given him the keys directly.

Same thing here. print() makes a promise that it can't keep because it entrusts the object to a function called getName(), which doesn't make that promise. The fact that getName() doesn't ACTUALLY change anything is irrelevant. It needs to DECLARE that it doesn't, so you have to add that "const" at the end.

Be a part of the DaniWeb community

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