J
J
Julia2016-09-17 19:20:48
C++ / C#
Julia, 2016-09-17 19:20:48

How can I change the code to make the example work?

Hi all. I have two classes

class Audioformat {
public:

    string titel() { return ""; }
    string info()  { return ""; }
};

int mp3_counter = 0;

class MP3_Format : public Audioformat {
public:
    
    string titel() { return  song; }
    string info()  { return "MP3"; }

private:
    string song;
};

and test:
bool test_A1_a() {
#ifdef A1_a
  Audioformat * af = new MP3_Format("Hey Joe");
  string info = af->info();
  string absp = af->titel();
  return (info == "MP3" && absp == "Hey Joe");
#else
  return false;
#endif
}

What needs to be changed in the MP_3 class in order for the code to work.
Now
string info = af->info();
string absp = af->titel();
return the result from the Audioformat class

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2016-09-17
@Julila

1. The title is a title, not a titel
2. Each new must be followed by a delete. It's better to wrap Audioformat* in std::unique_ptr which does the delete itself:

#include <memory>
std::unique_ptr<Audioformat> af(new Audioformat(""));
af->info(); af->title();
// Не нужен delete :D

3. Methods that can be called through a pointer to the base class must be declared as virtual. If the content of the base class methods does not make sense (as here), then it is better to declare them as purely virtual:
class Audioformat {
public:
    virtual string info() = 0;
};
class MP3_Format : public Audioformat {
public:
    string info() override { return "MP3"; }
};

override is optional, but highly recommended.
4. Virtual destructor:
class Audioformat {
public:
    virtual ~Audioformat() {}
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question