Open In App
Related Articles

C++ | Static Keyword | Question 4

Improve Article
Improve
Save Article
Save
Like Article
Like

Predict the output of following C++ program.




#include <iostream>
using namespace std;
  
class A
{
private:
    int x;
public:
    A(int _x)  {  x = _x; }
    int get()  { return x; }
};
  
class B
{
    static A a;
public:
   static int get()
   return a.get(); }
};
  
int main(void)
{
    B b;
    cout << b.get();
    return 0;
}


(A) 0
(B) Linker Error: Undefined reference B::a
(C) Linker Error: Cannot access static a
(D) Linker Error: multiple functions with same name get()


Answer: (B)

Explanation: There is a compiler error because static member a is not defined in B.

To fix the error, we need to explicitly define a. The following program works fine.

#include <iostream >
using namespace std;

class A
{
private:
    int x;
public:
    A(int _x)  {  x = _x; }
    int get()  { return x; }
};

class B
{
    static A a;
public:
   static int get()
   {  return a.get(); }
};

A B::a(0);

int main(void)
{
    B b;
    cout << b.get();
    return 0;
}


Quiz of this Question

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Similar Reads