Pointer to class in cpp

Pointers to Members

Declarations of pointers to members are special cases of pointer declarations. They’re declared using the following sequence:

  1. The declaration specifier:
    • An optional storage class specifier.
    • Optional const and volatile specifiers.
    • The type specifier: the name of a type. It’s the type of the member to be pointed to, not the class.
  2. The declarator:
    • An optional Microsoft-specific modifier. For more information, see Microsoft-Specific Modifiers.
    • The qualified name of the class containing the members to be pointed to.
    • The :: operator.
    • The * operator.
    • Optional const and volatile specifiers.
    • The identifier naming the pointer to member.
  3. An optional pointer-to-member initializer:
    • The = operator.
    • The & operator.
    • The qualified name of the class.
    • The :: operator.
    • The name of a non-static member of the class of the appropriate type.

As always, multiple declarators (and any associated initializers) are allowed in a single declaration. A pointer to member may not point to a static member of the class, a member of reference type, or void .

A pointer to a member of a class differs from a normal pointer: it has both type information for the type of the member and for the class to which the member belongs. A normal pointer identifies (has the address of) only a single object in memory. A pointer to a member of a class identifies that member in any instance of the class. The following example declares a class, Window , and some pointers to member data.

// pointers_to_members1.cpp class Window < public: Window(); // Default constructor. Window( int x1, int y1, // Constructor specifying int x2, int y2 ); // Window size. bool SetCaption( const char *szTitle ); // Set window caption. const char *GetCaption(); // Get window caption. char *szWinCaption; // Window caption. >; // Declare a pointer to the data member szWinCaption. char * Window::* pwCaption = &Window::szWinCaption; int main()

In the preceding example, pwCaption is a pointer to any member of class Window that’s of type char* . The type of pwCaption is char * Window::* . The next code fragment declares pointers to the SetCaption and GetCaption member functions.

const char * (Window::* pfnwGC)() = &Window::GetCaption; bool (Window::* pfnwSC)( const char * ) = &Window::SetCaption; 

The pointers pfnwGC and pfnwSC point to GetCaption and SetCaption of the Window class, respectively. The code copies information to the window caption directly using the pointer to member pwCaption :

Window wMainWindow; Window *pwChildWindow = new Window; char *szUntitled = "Untitled - "; int cUntitledLen = strlen( szUntitled ); strcpy_s( wMainWindow.*pwCaption, cUntitledLen, szUntitled ); (wMainWindow.*pwCaption)[cUntitledLen - 1] = '1'; // same as // wMainWindow.SzWinCaption [cUntitledLen - 1] = '1'; strcpy_s( pwChildWindow->*pwCaption, cUntitledLen, szUntitled ); (pwChildWindow->*pwCaption)[cUntitledLen - 1] = '2'; // same as // pwChildWindow->szWinCaption[cUntitledLen - 1] = '2'; 

The difference between the .* and ->* operators (the pointer-to-member operators) is that the .* operator selects members given an object or object reference, while the ->* operator selects members through a pointer. For more information about these operators, see Expressions with Pointer-to-Member Operators.

Читайте также:  Http intra volganet ru phone nums php

The result of the pointer-to-member operators is the type of the member. In this case, it’s char * .

The following code fragment invokes the member functions GetCaption and SetCaption using pointers to members:

// Allocate a buffer. enum < sizeOfBuffer = 100 >; char szCaptionBase[sizeOfBuffer]; // Copy the main window caption into the buffer // and append " [View 1]". strcpy_s( szCaptionBase, sizeOfBuffer, (wMainWindow.*pfnwGC)() ); strcat_s( szCaptionBase, sizeOfBuffer, " [View 1]" ); // Set the child window's caption. (pwChildWindow->*pfnwSC)( szCaptionBase ); 

Restrictions on Pointers to Members

The address of a static member isn’t a pointer to a member. It’s a regular pointer to the one instance of the static member. Only one instance of a static member exists for all objects of a given class. That means you can use the ordinary address-of (&) and dereference (*) operators.

Pointers to Members and Virtual Functions

Invoking a virtual function through a pointer-to-member function works as if the function had been called directly. The correct function is looked up in the v-table and invoked.

The key to virtual functions working, as always, is invoking them through a pointer to a base class. (For more information about virtual functions, see Virtual Functions.)

The following code shows how to invoke a virtual function through a pointer-to-member function:

// virtual_functions.cpp // compile with: /EHsc #include using namespace std; class Base < public: virtual void Print(); >; void (Base::* bfnPrint)() = &Base::Print; void Base::Print() < cout class Derived : public Base < public: void Print(); // Print is still a virtual function. >; void Derived::Print() < cout int main() < Base *bPtr; Base bObject; Derived dObject; bPtr = &bObject; // Set pointer to address of bObject. (bPtr->*bfnPrint)(); bPtr = &dObject; // Set pointer to address of dObject. (bPtr->*bfnPrint)(); > // Output: // Print function for class Base // Print function for class Derived 

Feedback

Submit and view feedback for

Источник

Pointers to Class Members in C++

Just like pointers to normal variables and functions, we can have pointers to class member functions and member variables.

Defining a Pointer of Class type

We can define pointer of class type, which can be used to point to class objects.

class Simple < public: int a; >; int main() < Simple obj; Simple* ptr; // Pointer of class type ptr = &obj; cout a; // Accessing member with pointer > 

Here you can see that we have declared a pointer of class type which points to class’s object. We can access data members and member functions using pointer name with arrow -> symbol.

Pointer to Data Members of Class

We can use pointer to point to class’s data members (Member variables).

Syntax for Declaration :

datatype class_name :: *pointer_name;

Syntax for Assignment:

Both declaration and assignment can be done in a single statement too.

datatype class_name::*pointer_name = &class_name::datamember_name ;

Using Pointers with Objects

For accessing normal data members we use the dot . operator with object and -> qith pointer to object. But when we have a pointer to data member, we have to dereference that pointer to get what its pointing to, hence it becomes,

and with pointer to object, it can be accessed by writing,

ObjectPointer->*pointerToMember

Lets take an example, to understand the complete concept.

class Data < public: int a; void print() < cout >; int main() < Data d, *dp; dp = &d; // pointer to object int Data::*ptr=&Data::a; // pointer to data member 'a' d.*ptr=10; d.print(); dp->*ptr=20; dp->print(); > 

The syntax is very tough, hence they are only used under special circumstances.

Pointer to Member Functions of Class

Pointers can be used to point to class’s Member functions.

return_type (class_name::*ptr_name) (argument_type) = &class_name::function_name; 

Below is an example to show how we use ppointer to member functions.

class Data < public: int f(float) < return 1; >>; int (Data::*fp1) (float) = &Data::f; // Declaration and assignment int (Data::*fp2) (float); // Only Declaration int main(0 < fp2 = &Data::f; // Assignment inside main() >

Some Points to remember

  1. You can change the value and behaviour of these pointers on runtime. That means, you can point it to other member function or member variable.
  2. To have pointer to data member and member functions you need to make them public.

Источник

Pointer to Class in C++

pointer to class in c++ - featured image

In this tutorial chapter we will study and understand the concept and Pointer to Class in C++ also known as Pointer to Object. For this it is first necessary to know the concept of pointers & classes in C++.

In general Pointers are variables that store address of other variables. A class in C++ is and Object oriented programming feature which enables programmer to create user defined complex datatypes (member variables) and functions(member functions) that operate on that data.

C++ Pointer to Class

Pointer to Class in C++

A class pointer is a pointer variable that stores address of an object of a class. As shown in the above diagram we have a class Rectangle with 2 data members and 1 member function. We have also created an object of that class named var1. Now we create a pointer variable *ptr of type Rectangle and assign the address of the object var1 to this pointer variable. As shown in the diagram the address of the object var1 is stored in the pointer variable ptr. Let us see an example of the same:

Example program of Pointer to Class in C++

#include using namespace std; class Rectangle < private: int length; int breadth; public: Rectangle(int l, int b) < length=l; breadth=b; >int getArea() < return 2*length*breadth; >>; int main() < // creating an object of Rectangle Rectangle var1(5,2); // parameterized constrcutor /* creating a pointer of Rectangle type & assigning address of var1 to this pointer */ Rectangle* ptr = &var1; /* calculating area of rectangle by using pointer ptr to call the objects getArea() function */ int area = ptr->getArea(); cout

Explanation
  • As you can see in the program we created an object of type Rectangle and passed length and breadth values in the parameterized constructor.
  • We then created a pointer named ptr of type Rectangle and assigned the address of var1 object to this pointer.
  • Then we calculated the area of the rectangle by calling the getArea() function of the class using this pointer (by using -> operator)
Pointer to Class Array in C++

As we just saw pointer to class, a pointer can also point to an an array of class. That is it can be used to access the elements of an array of type class.

pointer to class object array

As you can see in the Above diagram we have created an object array named var of class Rectangle. We have a pointer of class Rectangle named ptr and we have assigned the object array’s base address to this pointer ptr. So now our pointer ptr points to the first element in the object array. We can now iterate through the object array by using the increment operator in c++ like this : ptr++ This make the pointer to point ot the next array element of the object array and we can then access that element’s data members and member functions. Let us see and an example:

#include using namespace std; class Rectangle < private: int length; float breadth; public: void setData(int l, int b) < length=l; breadth=b; >int getArea() < return 2*length*breadth; >>; int main() < // creating an object array of Rectangle Rectangle var[2]; // setting values of array elements var[0].setData(5,2); var[1].setData(3,2); /* creating a pointer of Rectangle type & assigning address of var to this pointer */ Rectangle* ptr; ptr = var; /* calculating area of rectangles by using pointer ptr to call the objects getArea() function */ for(int i=0;i<2;i++) < cout<<"Area of Rectangle"<<(i+1)<<" : "<<(ptr+i)->getArea() return 0; >
Explanation
  • As you can see in the program we created an array object named var of type Rectangle and size 2 and set the values of both array elements using setData(int l, int b) function .
  • Next we created a pointer ptr of type Rectangle and assigned the object array’s address (base address) to this pointer. Pointer ptr now points to the first element of the object array
  • Lastly we access the member function of each element of the object array using pointer ptr & for loop to iterate through the object array.

Источник

Оцените статью