Inheritence allows our data structures to inherit certain member variables from a Base/Parent structure. In this entry I will only use public accessors, we will keep the topic of protected and private accessors for a later entry. When you build and run this program, you will notice the order in which output occurs. When we initialize our constructor in our Derived class, the Base class is initialized first. Derived hands control from main() to it's Base class, which then hands control back over to Derived. This is why the output,
occurs. Enjoy and Happy Coding!
Quote
Inside Base
Inside Base
Inside Derived
Inside Base
Inside Derived
occurs. Enjoy and Happy Coding!
//Inheritence
#include<iostream>
using namespace std;
class Base //Base Class
{
int val;
public:
Base(){};
Base(int i)
{
val = i;
cout<<"Base..."<<endl;
cout<<endl;
}
~Base()
{
cout<<"Destructing Base"<<endl;
cout<<endl;
}
void f()
{
cout<<"Inside Base"<<endl;
cout<<endl;
}
};
class Derived : public Base //Derived inherits Base's member variables
{ //as public. It does not inherit val from Base
//because val is private and not public or protected.
int val2;
public:
Derived(){};
Derived(int j) : val2(j)
{
cout<<"Derived..."<<endl;
cout<<endl;
}
~Derived()
{
cout<<"Destructing Derived"<<endl;
cout<<endl;
}
void f()
{
Base::f(); //When f() is called in Derived,
cout<<"Inside Derived"<<endl; //f() from Base will also be called
//by using the scope operator and making
} //a function call to f() in Base.
};
int main()
{
Base obj(8); //Initialize constructors
Derived obj2(6);
obj.f(); //Call Base f()
obj2.f(); //Notice output when Derived::f() is called
cout<<endl;
cin.get();
return 0;
}
1 Comments On This Entry
Page 1 of 1
Page 1 of 1
Trackbacks for this entry [ Trackback URL ]
Tags
My Blog Links
Recent Entries
Recent Comments
Search My Blog
0 user(s) viewing
0 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)
|
|



1 Comments










|