1. Gyanastra
  2. Programming Languages
  3. Programming in C++
  4. Classes Objects Static Members and Friends
Free lesson, no account needed 12 min read 26 practice questions after it
Asked in past papers7 times
  • ISRO2014
  • UGC NET201720162014201020092008

Programming Languages · Programming in C++

Classes Objects Static Members and Friends

Overview

A class is a user-defined type that bundles data and the functions that operate on that data; an object is a variable of that class type.
This lesson covers the C++ rules for class members, access control, the this pointer, static data members and static member functions, friend functions and friend classes, const member functions, constructors, and function objects.
These ideas are tested directly through definitions, statement-based questions, match-the-list items, assertion–reason items, and small code-output traces.
Before studying this lesson, you should know basic C++ syntax: declaring variables, functions, #include <iostream>, using namespace std;, and simple cout statements.

Key concepts

  • A class is a blueprint; an object is an instance of that blueprint. Each object has its own copy of every non-static data member, while member functions are shared by all objects.
  • Encapsulation is the bundling of data and the member functions that manipulate that data into one unit. Data hiding is achieved mainly by the private access specifier.
    Abstraction exposes only essential behaviour and hides implementation detail; it is a design principle, while encapsulation is the mechanism.
  • Access specifiers in a class: private members are accessible only inside the same class and by friends; protected members are accessible inside the same class, in derived classes, and by friends; public members are accessible everywhere.
  • In a class, the default access is private. In a struct, the default access is public. This is a common exam trap.
  • A member function declared inside a class belongs to the class. It may be defined inside the class body or outside using Class::function.
    A non-static member function has an implicit this pointer that points to the object on which it is called.
  • A const member function is written as return-type function(...) const. It cannot modify ordinary data members; inside it, this has type const Class*. A const object can call only const member functions.
  • A static data member belongs to the class, not to individual objects. Only one copy exists for the whole class. It must normally be defined outside the class, for example int A::c = 0;.
    It exists and may be initialised before any object is created.
  • A static member function has no this pointer. It can be called using the class name, for example A::get(), or through an object. It can directly access only static members; to access a non-static member it needs an explicit object.
  • A friend function is declared inside a class using the keyword friend, but it is not a member of that class.
    It has no this pointer for that class, yet it can access private and protected members of the class that grants friendship.
  • A friend class declaration friend class B; grants all member functions of class B access to the private and protected members of the granting class. Friendship is not reciprocal, not inherited, and not transitive.
  • A constructor is a special member function whose name is exactly the class name and which has no return type. It is called automatically when an object is created.
    A function defined with the class name is therefore a constructor, not a friend or static function.
  • A function object or functor is an object of a class that overloads operator(). Such an object can be used with function-call syntax, for example add(2, 3).
  • Inheritance models an “is-a” relationship. With protected inheritance, public and protected members of the base class become protected in the derived class, so an object of the derived class cannot access them directly from outside.

How it works

  1. Write a class with data members and member functions. Choose access specifiers carefully. Remember that class defaults to private.
  2. Create objects. Each object gets its own non-static data members. Static data members are not part of any single object; they belong to the class.
  3. When a non-static member function is called, the compiler passes the address of the calling object as the hidden this pointer. Inside the function, this->member means the member of that object.
  4. Access control is applied at class level, not object level. A member function of class A can access private members of any object of class A, not only the object through which it was called.
  5. A static data member is declared inside the class with static and defined outside the class. It is created once, before main begins execution, and is shared by all objects.
  6. A static member function is declared with static. It has no implicit object and therefore no this pointer. It is called as Class::function() or object.function().
  7. A friend declaration grants access but does not make the function or class a member. The friend declaration may appear in any access section; the section does not change its effect.
  8. A constructor runs automatically at object creation. It initialises the object. A const member function is used when an object must be read but not modified.
Figure. Notice that member functions split into non-static, which has a this pointer, and static, which has none. A friend declaration is not a member but grants special access.

Worked examples

Example 1 — static data member counter.

#include <iostream>
using namespace std;
class A {
public:
    static int c;
    A() { c++; }
};
int A::c = 0;
int main() {
    A a1, a2, a3;
    cout << A::c << " " << a1.c;
}

Trace: A::c starts at 0. Creating a1 runs the constructor and increments it to 1. a2 makes it 2, a3 makes it 3. A::c prints 3. a1.c denotes the same shared static member, so it also prints 3.
Answer: 3 3

Example 2 — friend function accessing private data.

#include <iostream>
using namespace std;
class P {
    int x;
public:
    P(int v = 5) : x(v) {}
    friend void show(P p);
};
void show(P p) { cout << p.x; }
int main() {
    P p(10);
    show(p);
}

show is a friend, not a member. It receives p by value and accesses p.x, which is private. The value passed is 10.
Answer: 10

Example 3 — this pointer and chained calls.

#include <iostream>
using namespace std;
class X {
    int a;
public:
    X(int v = 1) : a(v) {}
    X& inc() { ++a; return *this; }
    void show() { cout << a; }
};
int main() {
    X x;
    x.inc().inc().show();
}

x is created with a = 1. The first inc() increments it to 2 and returns a reference to x. The second inc() increments it to 3 and returns the same reference. Then show() prints 3.
Answer: 3

Example 4 — const member function.

#include <iostream>
using namespace std;
class C {
    int n;
public:
    C(int v = 7) : n(v) {}
    int get() const { return n; }
    void set(int v) { n = v; }
};
int main() {
    const C c(5);
    cout << c.get();
}

c is a const object with n = 5. get() is a const member function, so it can be called on a const object. set() is non-const and would not compile if called on c.
Answer: 5

Example 5 — statement type on friendship.
Statement I: Friendship is not inherited.
Statement II: Friendship is symmetric: if A is a friend of B, then B is a friend of A.
Analysis: If class A declares friend class B;, B can access A’s private members, but A does not automatically get access to B. So friendship is not symmetric. If B is a friend of A, a class derived from B is not automatically a friend of A; friendship is not inherited.
Answer: Statement I is true, Statement II is false.

Comparison

Access specifierSame class member functionsDerived class member functionsFriendsOutside code or object
privateYesNoYesNo
protectedYesYesYesNo
publicYesYesYesYes
Base class memberpublic inheritanceprotected inheritanceprivate inheritance
publicpublic in derivedprotected in derivedprivate in derived
protectedprotected in derivedprotected in derivedprivate in derived
privateinaccessibleinaccessibleinaccessible

With protected inheritance, public and protected base members become protected in the derived class. Therefore an object of the derived class cannot directly access those base members from outside.

FeatureNon-static member functionStatic member functionFriend functionConst member function
Belongs to classYesYesNoYes
Has this pointerYesNoNoYes, but type is const Class*
Can access private membersYesYes, as a memberYes, if declared friendYes
Can be virtualYesNoNoYes
Called using class nameNoYesNo, it is an ordinary functionNo
FeatureStatic data memberNon-static data member
CopiesOne per classOne per object
Part of objectNoYes
InitialisedBefore any object is createdBy constructor or initialiser
AccessClass::member or object.memberobject.member or this->member
Can be of its own class typeYes, because it is not stored inside each objectNo, an object cannot contain itself directly
FeatureFriend functionMember function
Member of classNoYes
Has this pointer for the granting classNoYes, if non-static
Access to private membersYesYes
InheritedNoYes, subject to access rules
Declared with friendYesNo

Revision summary

  • A friend function is not a member; static, const, and virtual functions can be members.
  • A member function can access all members of its own class, including private members of any object of that class.
  • private supports data hiding; protected allows derived classes; public allows everyone.
  • A static data member is shared by all objects and must normally be defined outside the class.
  • A static member function has no this pointer and can be called as Class::function().
  • A const member function cannot modify ordinary data members; inside it, this is const Class*.
  • Friendship is not reciprocal, not inherited, and not transitive.
  • A friend class declaration gives all member functions of the friend class access to the granting class.
  • A constructor has the same name as the class and no return type.
  • A function object is an object of a class that overloads operator().
  • Under protected inheritance, an object of the derived class cannot directly access public base-class members.

Previous-year exam insights

  • Direct definition questions often ask which item is not a member of a class: remember friend function is not a member, while static, const, and virtual functions can be members.
  • Statement-based questions test friendship properties: not inherited, not symmetric, not transitive; friend declarations do not make a function a member.
  • Match-the-list questions pair static data members, static member functions, friend functions, and const member functions with properties such as “one copy per class”, “no this pointer”, and “can access private members”.
  • Assertion–reason questions test whether a static data member can be of its own class type, whether friendship is inherited, and whether a const member function changes the type of this.
  • Code-output questions usually involve a static counter, chained calls through this, a friend function reading a private member, or a const object calling a const member function.
  • A common trap is protected inheritance: an object of the derived class cannot access public base-class members directly because they become protected in the derived class.
  • Check first whether the function is a member or a friend, whether it has a this pointer, and which access specifier or inheritance mode applies.
  • Another trap is forgetting that a static data member needs an outside definition, and that a static member function cannot be virtual or const.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Distinguish clearly between a class and an object, and between static and non-static data members.
  • Apply private, protected, and public access rules to member functions, derived classes, friends, and outside objects.
  • Trace a static counter program and state the exact output.
  • Explain the type and use of the this pointer in non-static and const member functions.
  • Write and interpret a friend function and a friend class declaration, and state exactly which accesses are allowed.
  • List and apply the properties of friendship: not a member, not reciprocal, not inherited, not transitive.
  • Identify a constructor, a function object, a const member function, and a static member function from syntax alone.
  • Solve statement I/II, match-the-list, and assertion–reason items on static members and friends.
  • Predict code output involving chained this calls, friend access to private data, and const objects.
  • Avoid the standard traps: default private access in class, protected inheritance, missing static definition, and confusing friend with member.

Attempt the sub-topic test first, then the subject test.

Pages 1–2 of 2