C++, Need help with OOP
20 minutes ago, Atalia Chez said:I dont understand one thing. Why did you put int x,y after creating class Mathematics and before void input function.
In the following code:
class Mathematics { int x, y; public: void input() { cout << "Input two inetegers\n"; cin >> x >> y; } void add() { cout << "Result = " << x + y; } };
Nothing is "created" yet. It is the definition of the Mathematics class, describing what the class looks like and what it can do, the declaration, and the implementation of the member functions, which makes it a definition. No object of the class is created, or instantiated, yet.
In OOP, a class is meant to be a black box, a object that performs a certain functionality through its member functions. However, the actual internal implementation of such a class is meant to be hidden from the user.
As a simple analogy, lets take a television set. The television class offers functionality to the user: one can turn it on and off, change channels, etc. But the internals are hidden inside the casing.
To offer this same functionality in OOP, a class can have private members, only accessible from inside the class and "invisible" to the outside, and public members, which are accessible from the outside and form the class's interface.
The default for a class in C++ is private, and one can switch between public and private using the keywords:
class Example { //Any declarations here are private! public: //Any declarations here are public! private: //Private again! };
Thus, in @vorticalbox's example code, member variables x and y are private class members, only accessible from inside the Mathematics class and 'invisible' to the outside. Member functions input and add are public, and thus are accessible from the outside. input reads 2 integers from stdin and stores them as x and y inside the class's instance for which the member function is called. add adds both numbers together and prints the result to stdout.
int main() { Mathematics m; // Creating object of class m.input(); m.add(); return 0; }
The above piece of code is where a instance of the Mathematics class, called m, is actually created. One can create multiple instances of a class (try it) and each will have their own x and y inside. The code then simply calls both member functions on the instance.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now