1

can derived class access base class non-static members without object of the base class

class base
{
public:
    int data;
    void f1()
    {
    
    }
};
class derived : base 
{
public :
     void f()
    {
        base::data = 44; // is this possible
        cout << base::data << endl;
    }
};

why does the below one shows a error

class base
{
public:
    int data;
    void f1()
    {
    
    }
};
class derived : base 
{
public :
     static void f()
    {
        base::data = 44; // this one shows a error
        cout << base::data << endl;
    }
};

i could not find the answer at any wedsites

slugolicious
  • 15,824
  • 2
  • 29
  • 43
  • `data` is a **instance** member variable. In the second code snippet, `f` is a *static* member function. There is no active instance in a static member function. Thus, there is no `data` because there is no instance. The difference between instance vs. static members is covered in *any* remedial text on the C++ language. – WhozCraig Jan 18 '22 at 04:31
  • What would you expect it to mean to be able to access a non-static member of the class without an object of that class? Given that you understand what the difference is between non-static and static members is, why would you expect the second version to work at all? – Nathan Pierson Jan 18 '22 at 04:33
  • `base::data = 44;` is actually `this->base::data = 44;` (as `data` is not `static`). and in `static` method as`f`, you cannot use `this`. – Jarod42 Jan 18 '22 at 09:20

1 Answers1

3

In your 1st example

class derived : base 
{
    void f()
    {
        base::data = 44;
    }
};

f() is not-static. It works on an object of derived, which includes an object of base. So, base::data = 44; is equivalent to data = 44; and it accesses the member of the object.

In the 2nd example

class derived : base 
{
    static void f()
    {
        base::data = 44;
    }
};

function f() is static, so it does not have access to any object. There, base::data = 44; could mean static data member of base. But because data is non-static, the expression is ill-formed.

Eugene
  • 6,194
  • 1
  • 20
  • 31