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
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.