the code is probably bad written and I would like to know how it should be done correctly.
Thanks for help
For the following inheritance scheme: A→B→C
a) define classes assuming that class A is to be an abstract class
b) equip all classes with a virtual name method returning the class name
c) add virtual destructors
d) add a global function friend of class A so that it can perform the same function as in point b
#include <iostream>
using namespace std;
class A {
public:
A();
virtual void name();
{
return A;
}
friend void ffriend()
virtual ~A();
};
class B : public A{
public:
B();
virtual void name();
{
return B;
}
virtual ~B();
};
class C : public B{
public:
C();
virtual void name();
{
return C;
}
virtual ~C()
};
friend void ffriend(&A){
name.A();
}
Your code cannot compile and have a lot of syntax error
b) equip all classes with a virtual name method returning the class name
that means the profile can be
virtual const char * name();
or
virtual const char * name() const;
or
virtual std::string name();
or
virtual std::string name() const;
but not virtual void name()
a) define classes assuming that class A is to be an abstract class
so at least one method must be abstract, typically in your case this is name
For the following inheritance scheme: A→B→C
probably because I do UML for me the arrows are in the wrong direction, but A being abstract very probably C inherits B which inherits (realize) A
c) add virtual destructors
that is trivial, but do not forget to implement them, not only to declare them
d) add a global function friend of class A so that it can perform the same function as in point b
that typically means the function get a reference to A, notice in your case the declaration and the definition do not correspond, and the list of parameters (&A)
is invalid
An example can be :
#include <iostream>
class A {
public:
// default contructor is enough
virtual ~A() {} // c)
virtual const char * name() const = 0; // a) and b)
friend const char * ffriend(const A &); // d)
};
const char * ffriend(const A & a)
{
return a.name(); // or return "A" ?
}
class B : public A {
public:
// default contructor is enough
virtual ~B() {} // c)
virtual const char * name() const { return "B"; } // b)
};
class C : public B {
public:
// default contructor is enough
virtual ~C() {}
virtual const char * name() const { return "C"; } // b)
};
int main()
{
B b;
C c;
std::cout << b.name() << ' ' << c.name() << ' ' << ffriend(b) << std::endl;
}
Compilation and execution:
pi@raspberrypi:/tmp $ g++ -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
B C B
pi@raspberrypi:/tmp $
It is not very clear what name the friend function has to return, I supposed the real class name but it can be "A" either.
Note also in A the method name can be private to justify the presence of the friend method if I can say.