Interfaces, enums and friend keyword


abstract

Image credit: Onion Bulb

Interfaces, enums and friend keyword
Interfaces, enums and friend keyword are the basics of C++ development. By using interfaces, we give the classes an addon service to include more functions by implementing them in interfaces.
Enum can be defined a type or a way to give the primitive type your favorite name. Friend keywords provides insight to the classes or members which are private or protected.

Interfaces in C++
An interface behaves as an add-on for the object that implements it. With interface we have only pure virtual methods (i.e. un-implemented).At first, abstract class also look like an interface but it can contain some functions with statements in the brackets. Example


class InterfaceExample
{
public:
    virtual void MethodA() = 0;
    virtual void MethodB() = 0;
};


class AbstractExample
{
public:

 virtual void MethodA();
 virtual void MethodB();
 void MethodC();
 {
 //body of the method

 }

  
};



“A virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature” – wikipedia

“A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract” – Wikipedia

Enums
The enum keyword is used to create an enumerated elements in name-list. The var=list is an optional keyword.

Example

enum month 
{ 
JANUARY=1, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
};

for( int monthcount = JANUARY; monthcount <= DECEMBER; monthcount++)
{
  std::cout << monthcount  << std::endl;
}

Output

1
2
3
4
5
6
7
8
9
10
11
12

Friend functions

The Private and Protected members can not be accessed outside the class
A friend member can view the hidden members of the class by making them friends to the class


#include <iostream>

using namespace std;

int AddToFriend(int x);
class CPP_Tutorial
{
int private_data;
friend int AddToFriend(int x);
public:
CPP_Tutorial()
{
private_data = 5;
}
};
int AddToFriend(int x)
{
CPP_Tutorial var1;
return var1.private_data + x;
}
int main()
{
cout << "Added Result for this C++ tutorial: "<< AddToFriend(4)<<endl;
}

Output

Added Result for this C++ tutorial: 9
reference http://www.codersource.net/2010/02/11/c-tutorial-friend/