C++: How to access member variables inside a member function

Started by
4 comments, last by dgrat 15 years, 6 months ago
Hi, I've got a little problem. I'm coming from the Java development, and there, I'm used to create a class with a member variable. The constructor has an argument with the same name. In the constructor, I make this argument to a member variable. Like this. class Blabla int variable; void Blabla(int variable){ this.variable = variable; } } Is there something similar to the "this." Keyword in C++? I know, normally, you write m_ before the variable. But somehow, I don't like that style. I just want to point in which focus the variable is, that I address.
Advertisement
Quote:Original post by Felix Ullrich
Hi,

I've got a little problem.

I'm coming from the Java development, and there, I'm used to create a class with a member variable. The constructor has an argument with the same name. In the constructor, I make this argument to a member variable.

Like this.


class Blabla

int variable;

void Blabla(int variable){

this.variable = variable;

}

}



Is there something similar to the "this." Keyword in C++?

I know, normally, you write m_ before the variable. But somehow, I don't like that style. I just want to point in which focus the variable is, that I address.



Yes, there is "this" keyword in C++. However, this is a pointer, so you should use the "arrow" sign instead of the "dot" sign to access your member variables.

class Blaba {
int variable;
Blabla(int variable) {
this->variable = variable;
}
};
C++ has the this keyword, however since it's a pointer to the current object you need to do this->variable and use the '->' operator as opposed to the '.' operator, which is used for value or reference types.

EDIT: Damn ninjas [razz]
Quote:Original post by Felix Ullrich
void Blabla(int variable){

this.variable = variable;

}

Constructors don't return anything, not even void. And the idiomatic C++ way to initialize member variables is to, well... initialize them instead of assigning them (after default initialization).

Blabla(int variable) : variable(variable) {}

The thing after the colon is called an "initialization list". Google it. It's cool.
Thanks a whole lot.

The arrow was what I needed. But this initialization list is just gorgeous. Thanks a lot for this.

I hope, the questions will be somewhat more advanced in time ;)
you dont need a pointer to the current object to get access to a member variable. also there are different ways to get an object of a class.... the simpliest way is the following...

class foo{private:   int bar;public:   void foobar();}void foo::foobar(){   std::cout<<bar<<std::endl;}


also if you want to use your point:
(*this).bar;
i thought java has pointers too?

or maybe
foo::bar;

the best you can do, is to use seperate function arguments or "::" or to learn C.

This topic is closed to new replies.

Advertisement