Windforces
Windforces

Reputation: 323

Initializing member variables in member functions

So I'm now implementing a c++ program and the thing is that I don't know whether the context below is possible or not.

class Foo{
     private:
          int a;
       public:
          Foo(int _a) : a(_a){

           }   

          void func(int _a) : a(_a){
              //implementation shows here
         }   
 }; 

As you can see here, there are member function which initializes a member variable in a manner like a constructor do. Is it possible?

Upvotes: 1

Views: 89

Answers (2)

Roddy
Roddy

Reputation: 68023

No. Initialization lists can only be used with constructors.

func would have to look like this.

      void func(int _a) {
         a = _a; 
          //implementation shows here
     } 

Obviously func can't initialise references, and the Foo constructor will be called before func can ever run...

Upvotes: 3

Bathsheba
Bathsheba

Reputation: 234645

No it's not possible and doesn't make much sense: member initialisation is only performed on construction.

In the function func, you're setting the member variable to something else, and assignment does that job perfectly well.

Upvotes: 4

Related Questions