Greg
Greg

Reputation:

C++ errors in code

I have this code (question from exam) and there are many errors in the code, here is the code:

 class A
 {
   int z;
   static int y;
   public:
     A() {(*this).incrementY();}
    int x () { y=y+2; return z;}
    static int getY(){ return z;}
    void incrementY() {y++}
 };
 class B: A
 {
   public:
    B (): A() {(*this).incrementY();};
 };
 class C : public B
 {
   public:
    C(): B() {(*this).incrementY;() }
 };

 int main()
 {
   A::x();
   A a;
   a.getY();
   A::getY();
   B b;
   C c;
   C::getY();
   b.x();
 }

There is a private inheritance. This means that all the methods and variables in B become private to any class that inherits from B?

Upvotes: 0

Views: 237

Answers (3)

dirkgently
dirkgently

Reputation: 111130

There are so many that you cannot but get tired. Here are some:

void incrementY() {y++}

No ; after y++.

24.   A::x();

Non static member cannot be invoked via a class name.

25.   A a;

No definition of static member y. If y was a const this would've been okay. This is a bit tricky so I'll quote.

9.4.2 Static data members

  1. The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void [...]

  2. If a static data member is of const effective literal type, its declaration in the class definition can specify a constant-initializer brace-or-equal-initializer with an initializer-clause that is an integral constant expression. A static data member of effective literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a constant-initializer brace-or-equal-initializer with an initializer-clause that is an integral constant expression. In both these cases, the member may appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

26.   a.getY();
27.   A::getY();

Illegal reference to non-static member A::z.

Taken care of by first observation.

28.   B b;
29.   C c;
30.   C::getY();

getY() is a private member of B, not visible to C, let alone be public.

31.   b.x();

The member function x() inherited from A is private.

Upvotes: 3

Ed James
Ed James

Reputation: 10607

You are correct there (although it actually means that all A's methods become inaccessible).

However, there are a few other problems:

A::x() // will not work as x is not static.
a.getY() // will not work as getY() is static.
C::getY() // Cannot access getY()

Upvotes: 0

MSN
MSN

Reputation: 54594

Yes, that is correct, although you could just compile it with any number of online C++ compilers to verify.

Upvotes: 0

Related Questions