Next, lets take a look at an example header file: Math.h
// Math.h
// Header file for the Math class
#pragma once
// Math class definition
static class Math
{
public:
// given base and exponent, calculate value
static int pow(int base, int exp);
};
#pragma once
is a preprocessor directive(like #include
) that tells the compiler
to only include this header once, regardless of how many times it has been imported in the programstatic
keyword meaning we don’t need to instantiate this class before using. Otherwise, we
need to do: Math math = new Math();
math.pow(2, 8);
this is helpful for a utility class such as this math class. Notice that the static class is only supported by Visual Studio, most the cases, people only use static member function instead of class.
Next, let’s take a look at the implementation of this class, the .cpp file:
#include "stdafx.h"
#include "Math.h"
int Math::pow(int base, int exp)
{
int result = 1;
for (int i = 0; i < exp; i++)
{
result = result * base;
}
return result;
}
Let’s take a look at the below example:
Person.h
#pragma once
#include <string>
class Person
{
private:
std::string firstName;
std::string lastName;
int age;
public:
Person();
Person(std::string fName, std::string lName);
Person(std::string fName, std::string lName, int age);
~Person();
void SayHello();
};
Person.cpp
#include "stdafx.h"
#include "Person.h"
#include <iostream>
Person::Person()
{
}
Person::Person(std::string fName, std::string lName)
{
this -> firstName = fName;
this -> lastName = lName;
}
Person::Person(std::string fName, std::string lName, int age)
{
this -> firstName = fName;
this -> lastName = lName;
this -> age = age;
}
Person::~Person()
{
}
The way that we declare our objects is important for determining how we call the member functions or access the public member variables.
Person *pOne = new Person();
Person p;
Person &Ref = p;
pOne->SayHello();
p.SayHello();
pRef.SayHello();
The definition of encapsulation in C++ has two layers:
A namespace is a “scope container” where you can place your classes, variables, or other identifiers to prevent name conflicts. For ecample, “std” is a namespace when you use “std::cout” Again, the “::” symbol is called scope resolution operator that allows user gain access to certain function in certain namespace