Thread: passing class

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    39

    Unhappy passing class

    how can i pass a class variable to a public function of the class and then return the class variable with the modifications?

  2. #2
    Unregistered
    Guest
    You don't need to pass a class variable to a class function. The class function has access to all class data variables already. like this:

    Code:
    #include <iostream.h>
    
    class Sample
    {
      public:
        Sample();
        int getData();
        void ModifyData();
      private:
        int data;
    };
    
    Sample::Sample() : data(3)
    {}
    
    int Sample::getData()
    {
      return data;
    }
    
    void Sample::ModifyData()
    {
      data += 4;
    }
    
    int main()
    {
      Sample sample;
      cout << "data before modification = " << sample.getData() << endl;
      sample.ModifyData();
      cout << "data after modification = " << sample.getData() << endl;
      return 0;
    }
    if you want to display modified variable directly from ModifyData you could do this:

    Code:
    #include <iostream.h>
    
    class Sample
    {
      public:
        Sample();
        int getData();
        int ModifyData();
      private:
        int data;
    };
    
    Sample::Sample() : data(3)
    {}
    
    int Sample::getData()
    {
      return data;
    }
    
    int Sample:: ModifyData()
    {
      data += 4;
      return data;
    }
    
    int main()
    {
      Sample sample;
      cout << "data before modification = " << sample.getData() << endl;
      cout << "data after modification = " << sample.ModifyData() << endl;
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Passing array through class constructor
    By sonicdoomx in forum C++ Programming
    Replies: 4
    Last Post: 05-10-2006, 01:42 PM
  3. Passing Pointer To Class In A Function
    By prog-bman in forum C++ Programming
    Replies: 11
    Last Post: 07-25-2004, 06:34 PM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. Passing functions by value in a class...
    By Sebastiani in forum C++ Programming
    Replies: 3
    Last Post: 05-30-2002, 05:57 PM