lundi 4 juillet 2016

Can I override a string return type functions in c++


I cannot understand why this does not compile:

#include<iostream>
#include<string>

using namespace std;


class Product {

public:
  virtual void print() = 0;
  virtual void slog() = 0;
  virtual void loft() = 0;
};

class Bike: public Product {

private:
  string s;

public:

  Bike(string x){ 
    s = x;
  }

  void print() { 
    std::cout << "Bike"; 
  }

  int slog() {
    return 4;
  }

  string loft() {
    return s;
  }
};

int main() {   
  string s("Hello");
  Product *p = new Bike(s);   
  p->print(); //works fine
  cout << p->slog();//works fine    
  cout << p->loft(); //error
  return 0; 
}
  1. The above code results in error. Why can't I override string class.
  2. I want to call loft() using the pointer p.
  3. Is there any way to achieve this using pointer object to abstract class Product

Aucun commentaire:

Enregistrer un commentaire