Reputation: 1017
In python we may use self keyword to declare class variables within a member function of the class which can be subsequently used by other member functions of the class. How to do such a thing in C++.
Python Code:
class abc():
{
def __init__(self):
self.help='Mike' #self.help is the class variable and can be used in other methods
def helpf():
morehelp=self.help+' Bike'
}
C++ code:
class abc
{
public:
abc();
public:
void helpf(void);
};
abc::abc()
{
string help="Mike";
}
void abc::helpf()
{
string morehelp=this->helpf+" Bike";// this keyword sounded like the one but...
}
Upvotes: 0
Views: 3577
Reputation: 35089
This works in Python because Python allows you to add a attribute to an object from anywhere simply by assigning to it. It attaches to that object, rather than the object's class. In keeping with Python's dynamic language philosophy, and particularly with its lack of variable declarations, all of this - including the decision about which attributes do or don't exist - happens at run time.
C++'s explicitly does not have a concept of one particular object having an attribute - all member variables are associated with the class, even if they take independent values on each instance. The set of all possible member variables, and which types they hold, is shared class-wide and set in stone at compile time. Because of this, what you're asking for basically doesn't make sense in C++.
Upvotes: 0
Reputation: 6461
You cannot declare class members inside functions in C++. You have to declare them outside functions, like in JAVA
class abc
{
public:
int publicInt; // This is a public class variable, and can be accesed from outside the class
int abc();
private:
float privateFloat; // This is private class variable, and can be accesed only from inside the class and from friend functions
void helpf(void);
};
Upvotes: 1
Reputation: 620
that is not possible. Declaring variables inside a member function are local to that member function. If you want to use variables in your member function you have to declare class variables.
Upvotes: 0
Reputation: 55897
There is no way to do such thing in C++. You should declare members in class, not in functions.
Upvotes: 3