I'm aa guy from C and just began to learn C++ few months ago, specifically about the OOP. So my question here is more about general OOP than about C++.
If someone is so nice to give me a brief answer or explanation to my questions:
1. I have a class with a constructor to initialize the data members' value. For example:
So, is it ok, if I put a new method into this class that can set the data members' value? e.g setVal(double r, double i) { re = r; im = i }
I mean here, in main() I have an object of this class Complex and I use it as a variable. Isn't an object like a value of a class just like the value of a variable? So is the new method setVal() still in the concept of OOP or not?
Yes you can add the method, and yes it fits in with the concept of OOP. What are commonly referred to as 'sets and gets' are very common methods for classes, setting member variable values and retrieving member variable values. It fits in with the OO principle of encapsulation.
I'm not sure I understand what you're getting at with the
Isn't an object like a value of a class just like the value of a variable?
A note on bnbertha reply:
gets and sets (or getter and setters) are also call Accessor methods.
Sometimes only the 'get' method is referred to as the Accessor method and a method that changes the state of an object is an update method, a modifier method, or a mutator method.
Thanks for the quick replies both of you!
what i meant with:
Isn't an object like a value of a class just like the value of a variable?
is the relationship between an object z1 of the class Complex is just like between a variable int a and the value 3, if we define it like a=3.
I think i got the wrong idea here, but its just I dont know the right one.
No it's a different relationship. A variable can only have one value, a class can have many objects. In terms of C the relationship between a class and it's members is more like a typedef structs' relationship with it's fields.