1 Replies - 1126 Views - Last Post: 02 April 2007 - 08:34 AM Rate Topic: -----

#1 krazykrisi  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 16-January 07

pointers to member functions

Posted 02 April 2007 - 07:19 AM

I am not quite sure how to use pointers when I want to point to a member function of a class from main. Can someone help me with this? Explain how this works. Here is what I have to do and my code:
/*2.	Create a class called Tank that describes the attributes of an armored vehicle. 
	Create a program that uses this object. Using pointer notation, access the member functions, 
	for an instance of this class.*/
//p. 467, ptrobjs.cpp
//array of pointers to objects
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Tank
{
   protected:
	  char color, amunition;
		  int guns, pass;
   public:
	  void setColor()
	  {
		 cout << "Enter color of the tank: ";
		 cin >> color;
	  }
	  void setAmunition()
	  {
		  cout << "Enter type of amunition: ";
		  cin >> amunition;
	  }
	  void setGuns()
	  {
		  cout << "Enter number of guns: ";
		  cin >> guns;
	  }
	  void setPass()
	  {
		  cout << "Enter number of passengers tank can hold: ";
		  cin >> pass;
	  }
	  void printInfo()
	  {
		 cout << "\n   Color: " << color;
		 cout << "\n   Ammunition: " << amunition;
		 cout << "\n   Guns: " << guns;
		 cout << "\n   Passengers: " << pass;
	  }
};
///////////////////////////////////////////////////////////////
int main()
{
   Tank tank1;
   
   tank1.setColor();
   tank1.setAmunition();
   tank1.setGuns();
   tank1.setPass();

   tank1.printInfo();
   int x;
   cin >> x;
   return 0;
}  //end main(}


Is This A Good Question/Topic? 0
  • +

Replies To: pointers to member functions

#2 horace  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 768
  • View blog
  • Posts: 3,832
  • Joined: 25-October 06

Re: pointers to member functions

Posted 02 April 2007 - 08:34 AM

you can set up a pointer to a member function and call it so
//   points to a member of Tank that takes ()
typedef  void (Tank::*TankMemberFunc)();

int main()
{
   Tank tank1;
  
   tank1.setColor();
   tank1.setAmunition();
   tank1.setGuns();
   tank1.setPass();

   tank1.printInfo();
   //  pointer to member function
   TankMemberFunc pFunc = &Tank::printInfo;
   // call member function
   (tank1.*pFunc)(); 
   int x;
   cin >> x;
   
   return 0;
}  //end main

in this case the statement
   (tank1.*pFunc)(); 

calls printInfo()
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1