Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 7.11.1: Pointer to Class Member

---
jupytext:
  formats: md:myst
  text_representation:
    extension: .md
    format_name: myst
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

Chapter 7.11.1: Pointer to Class Member

Adapted from: “Object-Oriented Programming Using C++” by Ira Pohl (Addison - Wesley)

Program that demonstrates pointers to class members in C++

In file showhide.cpp

showhide.cpp
/*********************************************************************

  Filename:  showhide.cpp
  Chapter:   7      Ad Hoc Polymorphism
  Section:   7.11   Pointer Operators
  Compiler:  Borland C++     Version 5.0       Summer 1996
  Object Oriented Programming Using C++, Edition 2   By Ira Pohl

*********************************************************************/

//Pointer to class member.

#include <iostream>           // Changed iostream.h to iostream. MK.

using namespace std;          // Added. MK.

class X {
public:
   int  visible;
   void print()
      { cout << "\nhide = " << hide
             << " visible = " << visible; }
   void reset() { visible = hide; }
   void set(int i) { hide = i; }
private:
   int  hide;
};

typedef void (X::*pfcn)();

int main()
{
   X  a, b, *pb = &b;
   int X::*pXint = &X::visible;
   pfcn pF = &X::print;

   a.set(8); a.reset();
   b.set(4); b.reset();
   a.print();
   a.*pXint += 1;
   a.print();
   cout << "\nb.visible = " << pb ->*pXint;
   (b.*pF)();
   pF = &X::reset;
   (a.*pF)();
   a.print();
   cout << endl;
}

Compilation Process

The above program is compiled and run using Gnu Compiler Collection (g++):

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + \
    "Cpp_Code/Chapter_7_11_1_Pointer_to_Class_Member"
os.chdir(code_dir)
build_command = os.system("g++ showhide.cpp -w -o showhide")

Execution Process

exec_status = os.system("./showhide")

hide = 8 visible = 8
hide = 8 visible = 9
b.visible = 4
hide = 4 visible = 4
hide = 8 visible = 8