C++ Programming (operator overloading)

Operator overloading is a method of allowing existing operators to be overloaded so that when these operators are used with class objects, the operators have meaning appropriate to the new types.

Example:

class NumberClass{
public:
//Overloading assignment operator
const NumberClass& operator=(const NumberClass &);
private:
int a;
int b;
int c;
};

const NumberClass& NumberClass::operator=(const NumberClass& source)
{
a = source.a;
b = source.b;
c = source.c;
return *this;
}

main()
{
NumberClass A(1,1,1), B(2,2,2);
A=B; // Invoked the overloaded assignment function
return 0;
}

 

C++ Programming (using keyword const)

The keyword const can be used in two different ways:

• Non-constant pointer to constant data:
Pointer can points to other variable, but data to which it points can’t be modified.

• Constant pointer to non-constant data:
Pointer always point to the same memory location, but data can be modified.

Example:

int x=10, y=20;
const int* pXPtr = &x; //Non-constant pointer, constant data
int* const pYPtr = &y; //Constant pointer, non-constant data
pXPtr = &y; //Legal
*pXPtr = 20; //Error
pYPtr = &x; //Error
*pYPtr = 10; //Legal

More examples of using keyword const:

const1

C++ Programming (Memory allocation/deallocation)

When programming in C/C++, one of the important things to take note of is memory allocation and deallocation. Without proper memory allocation, you would most probably get into run-time error during execution. Without proper memory deallocation, you would have memory leaks.

In C, you use malloc( ) and free() for memory allocation/deallocation. In C++, you use new and delete.

Example of memory allocation in C:

TypeName *typeNamePtr;
typeNamePtr = malloc(sizeof(TypeName));
free(typeNamePtr);

Example of memory allocation/deallocation in C++:

int* pnPtr=0; char* pcChar=0;
pnPtr = new int; //Allocate space for pointer variable
pcChar = new char[20] //Allocate space for 20 char.
delete pnPtr;
delete[ ] pcChar;

Things to note:
• Unlike new, malloc does not provide any method of initializing the block of memory allocated.
• Also, new/delete automatically invokes the constructor/destructor
• Do not mix new with free and malloc with delete.

Introductory guide to pointers in C

Introduction
C is a very powerful programming language that are used by many software developers to develop different kinds of software. However, for a beginner, C is a rather difficult language to grasp. Much of the difficulties in learning C comes from the confusion over the concept of pointers. In this article, I shall explain the concept of pointers with the help of some code snippets.

Pointers, Addresses and Variables
A pointer is a variable that holds a memory address.

It is important to differentiate between a pointer, the address that the pointer holds, and the value at the address held by the pointer. This is the source of much of the confusion about pointers. We will illustrate this in the following code snippets:

int nVariable = 5;
int *pPointer = &nVariable;

The first statement declares a variable “nVariable” of type integer and assigns a value 5 to it.

The second statement declares a pointer variable that holds the address of an integer, and assigns the address of the variable “nVariable” to it.

So let just imagine the memory is a set of lockers. Each of these lockers has a locker number assigned to it for identification purposes. The first statement will do something like reserving the locker number “1234”, and put the value “5” into this locker. The second statement will do something like reserving the locker number “4321”, and then put the value “1234” into the locker. So the locker number “4321” is actually storing the locker number of the locker that stores the value “5”.

Indirection
The term “Indirection” refers to the method of accessing the value at the address held by a pointer.
The indirection operator (*) is also called the dereference operator. The following code snippets in C++ shall illustrate this method:

int nVariable = 5;
int *pPointer = &nVariable;
printf(“The output is %d”, *pPointer);

The output of the code snippets will be the number “5”. Remember that “pPointer” is a pointer variable that holds the address of the variable “nVariable”. Notice that we use “*pPointer” to assess the value hold by the variable “nVariable”, and this is what we call “Indirection”.

Conclusion
This article aims to provide a simple guide to understanding the concept of pointers, addresses and variables in C. Readers are assumed to have some basic knowledge in C.

C++ Programming (using friend class)

A class may name another function or another class as its friend. That gives the named function the right to access all private features (strangely, friends are so powerful!). This is a dangerous mechanism and shouldn’t be used unless necessary!

Characteristic of Friendship:
• Friendship is not mutual unless explicitly specified as such.
• Friendship is not inherited.
• Friendship is not transitive. Therefore, if class A is a friend of class B, and class B is a friend of class C, we cannot infer that class C is a friend of class A.

Common Usage:
• to allow nested classes to access the private members of the surrounding class;
• to access the private members of other nested classes;
• to allow the surrounding class to access the private members of nested classes.

Example: In linked list, the list and node objects
Syntax:

class A {
private:
……..
friend class B;
};

Note that class B above can access the private members of class A because class A declare it as a friend.
Examples:

class Surround
{
public:
class FirstWithin
{
friend class Surround; //Allows Surround to access private members
public:
int getValue();
private:
static int variable;
};
int getValue()
{ // inline member function of Surround
FirstWithin::variable = SecondWithin::variable;
return (variable);
}

private:
class SecondWithin {
friend class Surround;
public:
int getValue();
private:
static int variable;
};
static int variable;
};

C++ Programming (using keyword static)

In C++, when modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all the instances of the class.

When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.

The following example illustrates the usage of the keyword static:

class SavingsAccount {
public:
static void setInterest( float newValue ) // Member function that
{ currentRate = newValue; } // accesses only static members
private:
char name[30];
float total;
static float currentRate; // One copy of this member is shared among all instances
};

// Static data members must be initialized at file scope, even if private.
float SavingsAccount::currentRate = 0.00154;

 

C++ Programming (using this pointer)

In C++, the this pointer is a pointer accessible only within the member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.

Example:

void Date::setMonth( int mn )
{
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;
}

In the above example, all the three statements are equivalent.

One common usage of this pointer is for concatenating member function calls:
Example:

class Time {
public:
Time(int hour=0, int minute=0, int second=0); //Default constructor
Time& SetHour(int hour) { m_hour = hour;
return *this; }
Time& SetMinute(int minute) { m_minute = minute;
return *this; }
Time& SetSecond(int second) { m_second = second;
return *this; }
private:
int hour;
int minute;
int second;
};

main( )
{
Time t;
t.SetHour(18).SetMinute(30).SetSecond(20); //Concatenating member function calls
return 0;
}

C++ Programming: Classes and Objects (Part II)

In part II of my illustration on C++ Classes & Objects, I will give some code snippets as examples:

Example of Class declaration:

class String
{
public:
String(char *aString=0); //Constructor
~String(); //Destructor
int GetLength() const; //Member function
const char* GetContent() const; //Member function
void SetContent(const char* aString) //Member function
private:
int m_nlength; //Data member
char* m_szContent; //Data member
};

Examples of Member functions implementation:

int String::GetLength() const
{
return m_nLength;
}

Object Instantiation

#include “String.h”
main()
{
/* Create object using memory from stack */
String S1(“Hello”);
/* Create object using memory from heap */
String* pS1;
pS1 = new String(“Hello”);
cout << pS1->GetContent() << endl;
}

Derived classes:

class subClassName : public baseClassName
{
//private member declarations
public:
//public member declarations
};

C++ Programming: Classes and Objects (Part I)

In this 3rd installment of my own little C++ tutorial, I will talk about classes and objects in C++.

What are Classes ?
• A user-defined type
• A collection of variables combined with a set of related functions
• An extension of the concepts “struct”
• Mechanism used in C++ for data abstraction

A C++ class has the following associated attributes:
• Access Control
• Constructors and Destructors
• A collection of data members
• A collection of member functions
• An associated class tag name

Access Control
• Private (Only by own member functions)
• Protected (By own and child functions)
• Public (By all)

Constructor
• member functions with the same name as the class (classname)
• support the automatic initialisation of objects at their point of declaration
• can take arguments
• do not have return types

Destructor
• member function (~classname)
• automatically invoked when an object goes out of scope
• cannot take arguments
• does not have return type

Data Members

Data members are states or attributes of an object

An Example:
class String
{
private:
int flag = 0; // error !!! no explicit initialization
int length; // Data member
char *content; // Data member
} ;

Member Functions
• Member functions are public interface
• Member functions have full access privilege to the public, protected and private members of the class
• Member functions are defined within the scope of their class

Using inline functions for C++ Programming

In C/C++, we use the qualifier inline before a function’s return type in the function definition to “advise” the compiler to generate a copy of the function’s code in place to avoid a function call.

But why do we need to avoid function call? Well, the only reason is to reduce execution time, though it comes with a small disadvantage of increasing of program size. Function calls requires the program to insert parameters and return address into stacks before jumping to the entry point of the called function. The return address needs to be retrieved from the stack upon exit of the called function. All these are overheads to execution time, and if a certain function is to be called very frequently, it might be a good idea to make it an inline function.

So, just a little tip in C programming which might be useful.