I am trying to do this C++ tutorial. I am a beginner in C++ programming. I don't get why they use setValue and getValue in class Class1 and not setClass1. In the other tutorial they use setA and getA in the class class Class1. Here are the codes:
class Class1 {
int i;
public:
void setValue( int value ) { i = value; }
int getValue() { return i; }
};
the second code is:
class A{
int ia;
public:// accessor method because they are used to access a private date member
void setA ( const int a);
int getA ()const;
int getA ();
};
Please help...
The names are arbitrary, you can use any function names you wish (subject to language rules, of course).
However, although you can use xyzzy() and plugh() as getter and setter, it's not really a good idea.
You should use something that indicates the intent of the call, such as getTemperature() or setVelocity(). And these don't even have to map one-to-one to internal fields since encapsulation means the internal details should not be exposed.
By that, I mean you may have a getTemperatureC() for returning the temperature in Celsius even though the internal field is stored as Kelvins:
double getTemperatureC(void) { return kelvins - 273.15; }
void setTemperatureC(double t) { kelvins = t + 273.15; }
(or a getter/setter may use arbitrarily complex calculations).
Using getA() for a class A may well cause you trouble when you create class B to inherit from A but this is outside the scope of the language. But it's good programming practice to follow the guideline above (functions should indicate intent rather than internals).
I was confused on why they use the same name in get and set with the class name, and different get and set name on the other class. Will the set and get names affect the code?
The answer is No.
getter and setter are usually called accessor and mutators in a class. They are just member functions named according to some convention, easy for people who read the code to understand the purpose of those functions, so it is like common sense to name those member function starting with get if you try to access the member variables and starting with set if you try to change some member variables. The names can be any valid identifier.
So setValue or setA are just identifiers for those member functions. It will not affect the code.
Meanwhile, different class can have the same named getter or setters since those function names are in different class scope.
Related
AFAIK In C++, we call the getter/setter function as 'property'.
The getter/setter is used to get/set a member variable.
One of the advantages of doing this is that we can listen for change, like this:
// In header:
class XXX {
int m_width{};
void OnWidthChanged() {
// do something...
}
public:
int Width() const {
return m_width;
}
void Width(int val)
m_width = val;
this->OnWidthChanged();
}
};
// In CPP:
XXX my_xxx;
my_xxx.Width(123);
cout << my_xxx.Width() << endl;
Now I found static variable can be used to implement similar thing, in a non-OOP fashion I know it cannot handle multiple-instance, so let's just assume XXX is an object that has only 1 instance.
// In header:
int XXX_Width(bool set = false, int val = 0);
void XXX_OnWidthChanged();
// In CPP:
int XXX_Width(bool set, int val) {
static int width = 0;
if (set) {
width = val;
XXX_OnWidthChanged();
}
return width;
}
XXX_Width(true, 123);
cout << XXX_Width() << endl;
My question is, is there a name or term for this kind of functions functions like XXX_Width()?
I'm looking for a name so I can google search for related information.
I'm not asking for name for OnWidthChanged().
Lots of confusion about terminology here.
OOP simply means that you have autonomous classes with their functionality encapsulated. Both your examples use OO, though if they are bad or good design is another matter.
Now I found static variable can be used to implement similar thing, in a non-OOP fashion:
There is nothing non-OOP with your example. It is however probably bad OO design, since multiple instances of your class may access that same function. It is also bad design from a thread-safety perspective.
Sometimes, using static variables locally is perfectly fine though, like for example when implementing "singleton" classes.
In C++, we call the getter/setter function as 'property'
No, that is not a common term. Getter/setter functions are called members, or member functions. Or possibly public member functions, since by definition those must be public. Another term used for them is methods.
The term property is most often used to describe public member variables. Often RAD tools use the term property for such variables.
My question is, is there a name or term for this kind of functions?
A function which is specified by the caller, but called by someone else (the class, the OS, an interrupt etc) is universally called callback function. This is a fairly broad term.
In your case, you seem to use callback functions like "events" - an event is a kind of callback function but a higher level concept. Code like your example could be used for so-called "event-driven design", which is also popular among RAD tools.
The 1st point that should be made is that your "property block" or "getter/setter" are non-conformant. The expected declarations look like:
int Width() const;
void Width(const int);
So when you change the setter to: XXX& Width(int) it becomes clear that you aren't talking about "property blocks" or "getter/setters". So let's talk about what your setter does look like:
It makes a call after width changes. Such a call would typically be an interupt or a signal
It returns a non-const reference to the object. This is the behavior of an operator which notably do have outside class versions
Now let's talk about your function: int XXX_Width(bool set = false, int val = 0) You've set it up with default arguments such that it could behave as either the setter or the getter in your example, notwithstanding the weirdness of your getter's return.
Given the distinction between the 2 options you present, you seem to be asking:
Is there a name for using a functions static variable instead of defining a function and providing getter/setters for a member variable?
A function scoped static variable is called a static local variable.
One word of wisdom on static local variables:
A static local variable is different from a local variable as a static local variable is initialized only once no matter how many times the function in which it resides is called and its value is retained and accessible through many calls to the function in which it is declared [source]
As a C++ beginner, I didn't thought about that much until now, but if I want to access an attribute from inside a class itself, should I access the attribute directly or use a getter function?
class foo
{
public:
int getVal();
void bar();
private:
int val;
}
foo::bar()
{
int val = this->getVal();
// or
int val2 = this->val;
}
I would like to know that for
a) what is better design and (more importantly for me)
b) any performance differences (maybe because of the overhead calling the function)?
I normally use the getter method even inside the class in case I ever want to rename the attribute. But now I'm writing a method, which will access the attribute quite (very) often.
It depends. Getters may have synchronization and if called from a method that is already holding the lock may deadlock the application. Or, on the contrary, getters may count/log access to the resource. Or even, the class may be an interface on the byte buffer and getters/setters dynamically unmarshal/marshal the wire data, in which case calling getters and setters is unavoidable.
The only universal rule - be consistent across the code base and try to not overcomplicate the design.
Inside the class always use the attribute itself. The reason you have a getter is to make a certain value available to other classes. Be careful with automatically making getters for every attribute you use. It is considered bad design to expose the inner workings of a class. Sometimes it makes sense to make an attribute available, sometimes it is just for internal use and other classes have no business inspecting them.
If you like to know more about this google "getters setters evil" Some of the articles you may find are quite extreme but they will explain why they feel that way.
I disagree with #user3535256. Getters and setters should also be used inside private class functions. The idea behind getters and setters is to make code changes nice and easy. #StanE think of a situation where you're using your class member variable without getter functions and after some time you'd like to change the name to be more meaningful. This example forces you to change the member name in each place it's used. In case of using getter method for your variable only class getter function will be affected by this code change.
Basically, getter and setters are used to hide complexity, or better saying, to abstract details from out of a class. So they are not mandatory for using inside a class.
Simply I can say, if you don't have a getter, you don't need to make that, for using inside of the class.
But if you have a getter, you should always use that, whether inside or outside of the class, as you might have applied some logic to the raw value inside getter.
This depends on the internals of your class. Suppose you have a simple class that holds a value and you want to count how often that value was accessed but there are different getter methods (I have to admit it is a quite contrived example). Instead of doing the bookkeeping in each of the methods it is easier to do it only once and use the getter also inside the class:
class CountedValue{
private:
int value;
int counter;
public:
CountedValue() : value(0),counter(0) {}
int getValue() const {
counter++;
return value;
}
int getMinusValue() const {
return - getValue();
}
// ... possibly more methods to retrieve the value
int getCounter() const { return counter;}
}
Actually with setters the benefit of using them also inside the class becomes more evident. You usually want to do bookkeeping and define the invariants of a member only once and not each time it can change.
For example:
class Rational {
private:
int numerator;
int denominator;
public:
void setNumerator(int n) { numerator = n; }
void setDenominator(int d) {
assert(d != 0 && "division by zero");
denominator = d;
}
void set(int n, int d) {
setNumerator(n);
setDenominator(n); // no need to check for 0 again
}
}
I'm watching C++ tutorials on youtube, and I'm on a video titled Using Variables In Classes. In the video he explains that if we were to make variables public in classes, that it's bad programming. It'll work, but it's still bad programming. The program he wrote out consisted of a class with a private variable, and he used two functions to access the variable. Code looks like this:
#include <iostream>
#include <string>
using namespace std;
class MyClass {
public:
void setName(string x)
{
name = x;
}
string getName()
{
return name;
}
private:
string name;
};
int main()
{
MyClass TO;
TO.setName("Taylor");
cout << TO.getName();
}
My question is, why did we have to create a separate function to return name, instead of returning it in the first function? In my code, I returned name in the first function and it went well.
There might be cases when you want to set the variable, perform some other operations and then print the variable, hence the two functions.
If you just want to input the variable and print it, one function is enough.
Member functions that are prefixed with set are called setters, and member functions that are prefixed with get are called getters.
They can have other names too, of course, but those are the common naming conventions. The main idea is that
getters "get" (return) a variable from inside a class, while
setters "set" (change) a variable inside a class to some specific value.
For the rationale behind the use of getters and setters, see the answers here. They cover a lot of good points on why getters and setters are a good thing in object-oriented programming.
Declare variables are private and use public functions are interface to set and get variables is a best practice. Why is not returning value from set function is an implication of 'separation of concern rule'. Please read this to get more info about it http://en.wikipedia.org/wiki/Separation_of_concerns
Because otherwise you wouldn't be able to write code to get the name if you don't happen to also be setting the name.
Consider trying to write a function to print the name of a MyClass passed as a parameter:
void printName(MyClass my_class){
std::cout << my_class.getName() << "\n";
}
How would you write this with a setName function but no getName function?
In your trivial example you don't need getName but you don't actually need MyClass either. You could just write:
std::cout << "Taylor\n";
but clearly that is not the point of the tutorial.
I have a class that has the following variables/members:
First Name
Last Name
Age
Address
etc..
I want to create getter-methods for each of them that returns the values. This could become quite large depending on the class.
Is there a quicker or more object-oriented way that would allow me to do this just using one method? The only way I can think about is to have a method that takes a parameter of the name of the variable to be returned; however, the types for the method would change depending on if it was returning a string, int etc..
Does anyone have a solution?
Why do you need those values outside the class? If you have code that is not in Person that calls 4 or 5 Person GetWhatever() methods and glues the strings together, stuffs commas between them and so on, move that code into Person. Do that enough and no code outside Person needs to call your getters.
Some classes are logic-free, they just hold values, and they expect outside objects to do all the work. In C++, using a struct for that makes your intention clear. If you insist that code outside Person needs to arbitrarily access elements of Person, it's probably a struct, not a class. If you insist it's a class, prove it by adding some actual business logic to it.
No, there is no "better" way which is still object-oriented. You should define one public "getter" method for each private member variable which needs to be access outside the class. You should also define a setter method, if the variable is meant to be set from outside the class.
If you want easy to define setter/getter - make it on single member level. Make member template with setter/getter and define is as public element of your class:
template <class Type>
class Member {
public:
Member(const T& value = T()) : value(value) {}
void setValue(const Type& t) { value = t; }
T getValue() const { return value; }
private:
T value;
};
Use it in your class:
class Person {
public:
Member<std::string> firstName;
Member<std::string> lastName;
Member<std::string> address;
Member<unsigned> age;
};
And usage:
int main() {
Person one;
one.firstName.setValue("Joe");
one.age.setValue(33);
}
If your need some constraints (like range checking) then define some RangeCheckingMember template. If you need the members to be dependent on each others - then make relationship between them by pointers/references.
Consider making that parameter lookup using a template member function that takes a default value in a given type.
template<typename ValueType>
const ValueType& get(const KeyType& key, const ValueType& default value) {
...
};
You still have to enumerate (or otherwise list) a KeyType of all your values (or use std::string which might be fine in larger cases) and work back and forth with your storage on the ValueType.
So, this doesn't really help you much until you decide you need arbitrarily large or completely dynamic values. At this point, you need to implement a map which can hold any type which requires either hideous unions or a template wrapper derived class from a common base class used in the map.
The upside to this is that a getKeys() method can present all of the keys available in the class -- something quite useful for dynamic GUIs and message handling.
If you are using a library in which everything subclasses some Object class (QObject for example), you can use a map of (string, object) to hold all your data and then access it with:
Object get(string name) { return memebers[name]; }
members is std::map<std::string, Object>
You will need to use type casts of course.
Button* my_var = static_cast<Button*>(my_class.get("my_button"));
// get returns Object
You can also use Qt's property system if you use Qt. This is not standard c++, but qmake and moc work on many operating systems.
all right.since you know what you want.
void get(int flag, void *return_value)
get the return_value typd casting to what you want.
thanks
I'm trying to learn C++, Thanks to this article I find many similarity between C++ and Python and Javascript: http://www.cse.msu.edu/~cse231/python2Cpp.html
But I can't understand C++ Classes at all, they looks like Javascript prototypes, but not that easy.
For example:
//CLxLogMessage defined in header
class myLOG: public CLxLogMessage{
public:
virtual const char * GetFormat (){
return "Wavefront Object";
}
void Error (const std::string &msg){
CLxLogMessage::Error (msg.c_str ());
}
void Info (const std::string &msg){
CLxLogMessage::Info (msg.c_str ());
}
private:
std::string authoringTool;
};
Question: What is this Public/Private stuff at all!?
Edit: To be honest, I more enjoy C++ than Python, because I can learn truth meaning of everything, not simple automated commands, for example I preferred to use "int X" rather than "X" alone.
Thanks
myLOG is the name of the class. It inherits (look it up2) from CLxLogMessage and has the functions GetFormat (which is virtual and can be overridden by subclasses and called through base class pointers, look it up2), Error, and Info. It has the data member authoringTool which is a string.
The public and private stuff is access specifiers. Something in the private section can only be used by the class's member functions, and stuff in the public section can be used by anybody. There is another type of section called protected which means that only a class and its subclasses can access it, but nobody else1.
If you start adding stuff to a class without setting an access level first, it defaults to private.
You can have as many public, private, and protected sections as you want, in any order.
You need these different protection levels because you don't want other people messing with your data when you don't know about it. For example, if you had a class representing fractions, you wouldn't want someone to change the denominator to a 0 right under your nose. They'd have to go through a setter function which would check that the new value was valid before setting the denominator to it. That's just a trivial example though. The fact that Python does not have these is a shortcoming in the language's design.
All your questions would be answered if you had read a C++ book. There is no easy way out with C++. If you try to take one, you'll end up being a horrible C++ programmer.
1 You can let somebody else access private and protected members by declaring them as friends (look it up2).
2 Sorry for saying "look it up" so much, but it's too much information for me to put here. You'll have to find a good resource for these kinds of things.
Even though there's no way to give a comprehensive answer or anything near that, maybe think about it like this: classes are types. Consider this:
int n;
Here "int" is the name of a type, and "x" is a variable of type "int". There are basic types in C++, like "int", "char", "double". Now we can also make new, compound types from old types:
struct Foo
{
int n;
char c;
double d;
};
This defines a new type called "Foo", and Foo x; makes a new variable of that type. Now we can add some magic to the type "Foo":
class Foo
{
int n;
double d;
public:
Foo() : n(20), d(0.5) { } // "constructor"
};
The keywords struct and class almost mean the same thing, so we still have a compound type that has two member variables, n and d. However, this type also has a member function, and this one gets called every time you create a new Foo object. So when you say, Foo x;, then this variable's member value x.n will be set to 20 and x.d will be set to 0.5.
So that's that in a nutshell: Classes are types with built-in magic. And you are the magician.
The private and public is to do with data encapsulation, it means you can change the implementation of the class without affecting how it is used. I suggest reading up on some of the theory of object orientation.