S
Samineni
I have two problems in C++ which I couldn't properly understand.
Appreciate if you can explain/eloborate more on this.
Problem 1:
-----------------
class Base
{
public:
virtual int fun(int i=10)
{
cout<<"Base::fun()"<<endl;
cout<<"The value of i="<<i<<endl;
}
};
class Derived : public Base
{
public:
int fun(int i=20)
{
cout<<"Derived::fun()"<<endl;
cout<<"The value of i="<<i<<endl;
}
};
void main()
{
Base* bptr = new Derived();
bptr->fun();
}
output:
---------
Derived::fun()
The value of i=10;
Here my question, how the default value is assigned to 10 ?
Problem 2:
--------------
class Base
{
public:
virtual int fun()
{
cout<<"Base::fun( )"<<endl;
}
virtual int fun(int i)
{
cout<<"Base::fun(int )"<<endl;
}
};
class Derived : public Base
{
public:
class Base
{
public:
virtual int fun()
{
cout<<"Derived::fun( )"<<endl;
}
};
void main()
{
Derived dObj;
dObj.fun();
dObj.fun(10); // Gives compile error.
}
Here my question why Derived Class instance doesn't inherit the
non-overridden methods directly even the other fucntion is virtual. In
case of non-virtual functions I know about this problem, but in this
case (vitrual fucntions) I am not why the compiler is complaining about
the non-overridden method. ?
Appreciate if you can explain/eloborate more on this.
Problem 1:
-----------------
class Base
{
public:
virtual int fun(int i=10)
{
cout<<"Base::fun()"<<endl;
cout<<"The value of i="<<i<<endl;
}
};
class Derived : public Base
{
public:
int fun(int i=20)
{
cout<<"Derived::fun()"<<endl;
cout<<"The value of i="<<i<<endl;
}
};
void main()
{
Base* bptr = new Derived();
bptr->fun();
}
output:
---------
Derived::fun()
The value of i=10;
Here my question, how the default value is assigned to 10 ?
Problem 2:
--------------
class Base
{
public:
virtual int fun()
{
cout<<"Base::fun( )"<<endl;
}
virtual int fun(int i)
{
cout<<"Base::fun(int )"<<endl;
}
};
class Derived : public Base
{
public:
class Base
{
public:
virtual int fun()
{
cout<<"Derived::fun( )"<<endl;
}
};
void main()
{
Derived dObj;
dObj.fun();
dObj.fun(10); // Gives compile error.
}
Here my question why Derived Class instance doesn't inherit the
non-overridden methods directly even the other fucntion is virtual. In
case of non-virtual functions I know about this problem, but in this
case (vitrual fucntions) I am not why the compiler is complaining about
the non-overridden method. ?