What are the four pillars of object oriented programming, with regards to C++? I've googled and googled this subject, and there are different answers depending on which site you visit. What is your impression as to what the four pillars are? I've given my impression below, in the form of code snippets. Are these snippets the correct way to think of the four pillars?
Simple class / object:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
A(void)
{
value1 = 123;
}
int value1;
};
int main(void)
{
A a;
cout << a.value1 << endl;
return 0;
}
Pillar 1 encapsulation:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
A(void)
{
value1 = 123;
}
// Encapsulating the member variable by making it protected from code
// that exists outside of the class
protected:
int value1;
public:
int getvalue1(void)
{
return value1;
}
void setvalue1(const int value)
{
value1 = value;
}
};
int main(void)
{
A a;
cout << a.getvalue1() << endl;
return 0;
}
Pillar 2 inheritence:
#include <iostream>
using std::cout;
using std::endl;
// Base class
class A
{
public:
A(void)
{
value1 = 123;
}
protected:
int value1;
public:
int getvalue1(void)
{
return value1;
}
void setvalue1(const int value)
{
value1 = value;
}
};
// Inheriting class
class B: public A
{
public:
B(void)
{
value2 = 456;
}
protected:
int value2;
public:
int getvalue2(void)
{
return value2;
}
void setvalue2(const int value)
{
value2 = value;
}
};
int main(void)
{
B b;
cout << b.getvalue1() << ' ' << b.getvalue2() << endl;
return 0;
}
Pillar 3 abstraction (abstract class):
#include <iostream>
using std::cout;
using std::endl;
// Abstract base class (cannot be instantiated due to pure virtual member function)
class A
{
public:
virtual void talk(void) = 0;
};
// Inheriting class must implement pure virtual function talk()
class B: public A
{
public:
void talk(void)
{
cout << "Class B" << endl;
}
};
int main(void)
{
B b;
b.talk();
return 0;
}
Pillar 4 polymorphism:
#include <iostream>
using std::cout;
using std::endl;
// Abstract base class (cannot be instantiated due to pure virtual member function)
class A
{
public:
virtual void talk(void) = 0;
};
// Inheriting class must implement pure virtual function
class B: public A
{
public:
void talk(void)
{
cout << "Class B" << endl;
}
};
// Inheriting class must implement pure virtual function
class C: public A
{
public:
void talk(void)
{
cout << "Class C" << endl;
}
};
int main(void)
{
B b;
b.talk();
C c;
c.talk();
// Also see general function overloading as an example of polymorphism
// ie:
// int add(int a, int b) { return a + b }
// float add(float a, float b) { return a + b }
//
// Also see templates
// ie:
// STL containers
return 0;
}