Alright so I'm trying to creating something that is sort of like the properties in C# for my classes in C++.
for example. in C# i would do this:
int MaxHP { get; set; }
or, with backing field:
int MaxHP
{
get { return maxHP; }
set { maxHP = value; }
}
However so far with C++, I've only been able to replicate this with:
private:
int maxHP;
int maxEP;
public:
int GetMaxHP() { return maxHP; }
void UpSetMaxHP(int value){ maxHP += value; }
void DownSetMaxHP(int value){ maxHP -= value; }
int GetMaxEP(){ return maxEP; }
void UpSetMaxEP(int value){ maxEP += value; }
void DownSetMaxEP(int value){ maxEP -= value; }
I must be missing something in the way things should be designed. In C# the property would be access like a field. however in C++ I have to do functions which work differently when accessed from other objects.
I guess i could do:
public:
int MaxHP;
But that feels like I am sort of defeating the purpose. So my question is, Am i doing this right or is there a better, proper way of achieving this?
Rather than creating separate getter and setter functions, you can have a function which returns a reference which can be used either way:
public:
int &max_hp() { return maxHP; }
Unlike just delaring maxHP public, this allows you to place a breakpoint to see when the variable is accessed, and if you later want to add conditions or logging you can do so without changing your class interface.
This feature does not exist in C/C++. You could easily argue that it's a defect to be missing but not all languages are equal. The one thing Java has that C# doesn't is singleton object-like enums. It's otherwise, IMO, a bit of a dated language, but it still has one solid feature that's missing in C#.
So what I'm saying is, when you run into these things, often you do find a genuine weakness or a design flaw. It's good to ask if you're just missing something (hence my upvote) but as you learn what strengths and weaknesses different languages have, you'll learn which languages are good for which jobs and perhaps be effective at writing DSLs or language extensions earlier in your career than later.
C/C++ does not support anything like this by default, however it is commonplace to have functions such as int getHP() and void setHP(int) but there is kind of an operator 'hack' to make it function pretty close to how c#'s get/set works. But the code to work around this is very messy and can cause many bugs.
Example (2nd post): http://forums.codeguru.com/showthread.php?459696-GET-SET-in-C
To get rid of getters and setters functions in C++, I have written a simple macro that gets and sets most of data types that I use in my software. Templates also can be useful for that.
For example
#define GET_BOOL(name) bool is##name() const {return name##_;}
#define SET_BOOL(name) void set##name(bool name) {name##_ = name;}
#define GET_SET_BOOL(name) GET_BOOL(name) SET_BOOL(name)
Related
Below code came from a post about C++ interview questions here. I've never known this technique :) (though it's claimed a good one :)). My questions are: In which situation do we need to use it? Do you often see it in your real production/legacy code?
Question:
Implement a method to get topSecretValue for any given Something* object. The method should be cross-platform compatible and not depend on sizeof (int, bool, string).
class Something {
Something() {
topSecretValue = 42;
}
bool somePublicBool;
int somePublicInt;
std::string somePublicString;
private:
int topSecretValue;
};
Answer:
Create another class which has all the members of Something in the same order, but has additional public method which returns the value. Your replica Something class should look like:
class SomethingReplica {
public:
int getTopSecretValue() { return topSecretValue; } // <-- new member function
bool somePublicBool;
int somePublicInt;
std::string somePublicString;
private:
int topSecretValue;
};
int main(int argc, const char * argv[]) {
Something a;
SomethingReplica* b = reinterpret_cast<SomethingReplica*>(&a);
std::cout << b->getTopSecretValue();
}
It’s important to avoid code like this in a final product, but it’s nevertheless a good technique when dealing with legacy code, as it can be used to extract intermediate calculation values from a library class. (Note: If it turns out that the alignment of the external library is mismatched to your code, you can resolve this using #pragma pack.)
You can do this without reinterpret_cast. There is a trick using templates and friends that is outlined in the following blog post that demonstrates the technique:
Access to private members. That's easy!
This is certainly safer than the interviewer's approach, since it eliminates human error in re-creating the class definition. Is this approach good at all, though? The given question has some incredibly artificial constraints that would rarely apply to a 'real' project. If it's a C++ project and you have access to the header file, why not just add a getter? If it's not a C++ project, why are you so constrained in your definition of the interop class?
This is probably very basic but somehow I cannot figure it out.
Say I have a class A which embeds 42 Things, plus some common data:
class A {
Thing things[42];
int common_data[1024];
}
I would like each thing to have access to the common data, but I don't want to copy the data in each Thing object, nor pay the price of a pointer to it in each thing. In other word, I would like Thing to look like this:
class Thing {
int ident;
int f() {
return common_data[ident];
}
}
Of course here common_data is unbound. What is the canonical way to make this work?
FWIW I am working with a subset of C++ with no dynamic allocation (no "new", no inheritance, basically it's C with the nice syntax to call methods and declare objects); I am ideally looking for a solution that fits in this subset.
You can solve your issue by making the common_data attribute of Class A static. Static variables are shared by all members of class A, and will be accessible if you make it public.
class A
{
private:
Thing things[42];
public:
static int common_data[1024];
}
It can be accessed by doing...
A::common_data[index];
I am not sure if I understand the question correctly, but maybe this helps:
struct A {
Thing things[42];
int common_data[1024];
void foo(int index) {
things[index].doSomeThingWithCommonData(int* common_data);
}
};
struct Thing {
void doSomeThinWithCommonData(int* common_data) {
/* now you have access to common_data */
}
};
Your reasons for avoiding pointers/reference is based on irrational fears. "Copying" a pointer 42 times is nothing (read this word carefully) for the machine. Moreover this is definitely not the bottleneck of the application.
So the idiomatic way is to simply use dependency injection, which is indeed a slightly more costly action for you (if passing an array can be considered costly), but allows for a much more decoupled design.
This is therefore the solution I recommend:
struct Thing {
using data = std::shared_ptr<std::array<int, 1024>>;
data common_data;
Thing(data arg)
: common_data(arg)
{}
// ...
};
If the system is costrained, then you should benchmark your program. I can tell you already with almost absolutely certainty that the bottleneck won't be the copying of those 42 pointers.
I've recently begun learning c++ (no prior programming knowledge). I've used the book "Jumping into c++" By Alex Allain and i've found it most useful! However i've reached the chapters of classes, inheritence and polymorphism, and while i do understand most of it I just cannot wrap my head around this one problem.
In the book I am asked to solve the following problem:
Implement a sort function that takes a vector of pointers to an interface class, Comparable,
that defines a method, compare(Comparable& other), and returns 0 if the objects are the
same, 1 if the object is greater than other, and -1 if the object is less than other. Create a class
that implements this interface, create several instances, and sort them. If you're looking for
some inspiration for what to create—try a HighScoreElement class that has a name and a
score, and sorts so that the top scores are first, but if two scores are the same, they are sorted
next by name.
I've created the classes Comparable and HighScores:
class Comparable {
public:
virtual int compare(Comparable& other)=0;
};
class HighScore : public Comparable {
public:
HighScore(int, std::string);
virtual int compare(Comparable& other);
private:
int highscore;
std::string name;
};
If i try to overwrite the inherited function in HighScore, i am not able to compare, for instance the int highscore, with the int highscore of (Comparable& other), since i cannot access the other.highscore. Example below:
int HighScore::compare(Comparable& other){
if (highscore == other.highscore) {
return 0;
}
//...
}
I thought i could maybe change the virtual method to something like:
int HighScore::compare(HighScore& other){
if (highscore == other.highscore) {
return 0;
}
//...
}
Since that would allow me to access other.highscore (and i had hoped that i would work since HighScore also can be considered a Comparable. But alas no such luck. What should I do, i litterally have no clue on how to continue and i would appreciate any help i can get. Thanks :)
Indeed, trying to choose behaviour based on the run-time type of two or more objects is a bit fiddly in a single-dispatch language like C++.
The simplest solution is to use RTTI to determine whether the other object has a type comparable with ours:
int HighScore::compare(Comparable& other){
int other_highscore = dynamic_cast<HighScore&>(other).highscore;
if (highscore == other_highscore) {
return 0;
}
//...
}
This will throw an exception if the types aren't comparable, which is probably the best you can do.
Alternatively, you could implement a double-dispatch mechanism (such as the "Visitor Pattern"), involving two virtual functions. I'll let you research it yourself, since an example would be long-winded and not particularly inspiring.
Hopefully, you will soon learn how to do this using compile-time generics rather than run-time abstract interfaces, which is much more idiomatic in C++. If the book doesn't teach you that, throw it away and get one of these instead.
You can write a pulic getter function to get the score
class Comparable {
public:
int get_score() const = 0;
//
}
class HighScore : public Comparable {
public:
int get_score() const { return highscore; }
and then use that for comparison.
int HighScore::compare(Comparable& other){
if (highscore == other.get_score()) {
^^^^^^^^^^^
return 0;
}
//...
}
But since only the derived class has highscore member you should probably change what you pass to compare.
int HighScore::compare(HighScore& other)
OR move highscore member to the base class. Whichever males sense to you.
I'd suggest picking another book on the subject. Since this exercise seemed to be vague and doesn't give good understanding on polymorphism. The tricky part is that when you get Comparable in your compare method you have no clue, if it is HighScore or some other derived class. And in case if the class you are attempting to compare is not an instance of HighScore such terms as equal less and greater doesn't have any meaning. Thus there is no way to solve this correctly. You can of course use dynamic_cast to check if it is HighScore, but still if it doesn't there is no good answer if it greater, lesser or equal to something that isn't a HighScore.
Just imagine that there is something like class Color : public Comparable { exists. What should you return in case if you get Color to be compared with HighScore? Is blue bigger than 10, or Yellow less than 15, what red is equal to?
So I am new to c++ and I'm writing for a scientific application.
Data needs to be read in from a few input text files.
At the moment I am storing these input variables in an object. (lets call it inputObj).
Is it right that I have to pass this "inputObj" around all my objects now. It seems like it has just become a complicated version of global variables. So I think I may be missing the point of OOP.
I have created a g++ compilable small example of my program:
#include<iostream>
class InputObj{
// this is the class that gets all the data
public:
void getInputs() {
a = 1;
b = 2;
};
int a;
int b;
};
class ExtraSolver{
//some of the work may be done in here
public:
void doSomething(InputObj* io) {
eA = io->a;
eB = io->b;
int something2 = eA+eB;
std::cout<<something2<<std::endl;
};
private:
int eA;
int eB;
};
class MainSolver{
// I have most things happening from here
public:
void start() {
//get inputs;
inputObj_ = new InputObj();
inputObj_ -> getInputs();
myA = inputObj_->a;
myB = inputObj_->b;
//do some solve:
int something = myA*myB;
//do some extrasolve
extraSolver_ = new ExtraSolver();
extraSolver_ -> doSomething(inputObj_);
};
private:
InputObj* inputObj_;
ExtraSolver* extraSolver_;
int myA;
int myB;
};
int main() {
MainSolver mainSolver;
mainSolver.start();
}
Summary of question: A lot of my objects need to use the same variables. Is my implementation the correct way of achieving this.
Don't use classes when functions will do fine.
Don't use dynamic allocation using new when automatic storage will work fine.
Here's how you could write it:
#include<iostream>
struct inputs {
int a;
int b;
};
inputs getInputs() {
return { 1, 2 };
}
void doSomething(inputs i) {
int something2 = i.a + i.b;
std::cout << something2 << std::endl;
}
int main() {
//get inputs;
inputs my_inputs = getInputs();
//do some solve:
int something = my_inputs.a * my_inputs.b;
//do some extrasolve
doSomething(my_inputs);
}
I'll recommend reading a good book: The Definitive C++ Book Guide and List
my answer would be based off your comment
"Yea I still haven't got the feel for passing objects around to each other, when it is essentially global variables im looking for "
so this 'feel for passing object' will come with practice ^^, but i think it's important to remember some of the reasons why we have OO,
the goal (in it simplified version) is to modularise your code so as increase the reuse segment of code.
you can create several InputObj without redefining or reassignig them each time
another goal is data hiding by encapsulation,
sometimes we don't want a variable to get changed by another function, and we don't want to expose those variable globally to protect their internal state.
for instance, if a and b in your InputObj where global variable declared and initialized at the beginning of your code, can you be certain that there value doesn't get changed at any given time unless you want to ? for simple program yes.. but as your program scale so does the chances of your variable to get inadvertently changed (hence some random unexpected behavior)
also there if you want the initial state of a and b to be preserved , you will have to do it yourself ( more temp global variables? )
you get more control over the flow of your code by adding level abstractions with classes/inheritances/operation overriding/polymorphisms/Abtract and interface and a bunch of other concepts that makes our life easier to build complex architectures.
now while many consider global variable to be evil, i think they are good and useful when used properly... otherwise is the best way to shoot yourself in the foot.
I hope this helped a bit to clear out that uneasy feeling for passing out objects :)
Is using your approach good or not strongly depends on situation.
If you need some high speed calculation you can't provide incapsulation methods for your InputObj class, though they are recommended, because it will strongly reduce speed of calculation.
However there are two rules that your can follow to reduce bugs:
1) Carefully using 'const' keyword every time you really don't want your object to modify:
void doSomething(InputObj * io) -> void doSomething(const InputObj * io)
2) Moving every action related with initial state of the object(in your case, as far as I can guess, your InputObj is loaded from file and thus without this file loading is useless) to constructor:
Instead of:
InputObj() { }
void getInputs(String filename) {
//reading a,b from file
};
use:
InputObj(String filename) {
//reading a,b from file
};
You are right that this way you have implemented global variables, but I would call your approach structured, and not complicated, as you encapsulate your global values in an object. This will make your program more maintainable, as global values are not spread all over the place.
You can make this even nicer by implementing the global object as a singleton (http://en.wikipedia.org/wiki/Singleton_pattern) thus ensuring there is only one global object.
Further, access the object through a static member or function. That way you don't need to pass it around as a variable, but any part of your program can easily access it.
You should be aware that a global object like this will e.g. not work well in a multithreaded application, but I understand that this not the case.
You should also be aware that there is a lot of discussions if you should use a singleton for this kind of stuff or not. Search SO or the net for "C++ singleton vs. global static object"
in Java code convention is simple and obvious, in this style:
public:
int GetMyAge(){
return myAge;
}
void SetMyAge(int myAge){
this->myAge = myAge;
}
private:
int myAge;
(I know it's "again the same thing", but) I have read most of related questions on SO and I still don't know "the best one" and "the most official" way to do it in C++. It can't be just a matter of preferences, can it?
EDIT:
Seems like it can.
Best not to do it at all. Can your age actually be changed like that? Blindly providing getters and setters for all properties is a sign you have not designed your class properly.
The best style is the one that allows you and your team to make quality software that your clients continue to pay you for.
How does this style work for you and your team? Do you find it causes (or prevents) bugs? Do you find it easy to maintain the code? Do you bicker about the formatting?
Answer those questions and the answer to your question will arise out of them.
A simple answer: class names are capital in general in c++ (except for the std classes), methods are lower case, some frameworks like Qt prefer camelCase, however I prefer underscore_notation -- and so do the STL see eg. "auto_ptr".
Classes do not always have separate .h files, because here a .java file is split up into a .h header (for an entire package), and .cpp implementation files, one per class.
class TipicalCamelCase {
public:
/// mark the frequently used small functions inline in the class def.
inline int getMyAge() const;
void setMyAge(int myAge=5); // defaults go to the definition.
/// for efficiently setting more complex things.
void setMyStuff(const MyStuff& myStuff);
/// a tipical class-valued getter
/// (sometimes scoffed at since it can have memory leaks
/// if you dismiss the class but still use and don't copy MyStuff.)
const MyStuff& getMyStuff() const;
/// a safe getter, but forces copying-out MyStuff.
MyStuff getMyStuff() const;
private:
int myAge;
static const int zero=0; // allowed only in the new C++11 standard.
static const int one;
};
Some implementations/initializations (usually in separate TipicalCamelCase.cpp file):
const int TipicalCamelCase::one = 1;
int TipicalCamelCase::getMyAge() const{
return myAge;
}
void TipicalCamelCase::setMyAge(int myAge_){
myAge = myAge_;
}
Underscore style is the same but
int Tipical_camel_case::get_my_age() const
{
return my_age;
}
I prefer this as it looks cleaner both in the header and in the implementation files.
You can see that function headlines are lengthier than in java. Especially you'll see with templates (generics) 2 lines' header is typical, so it is worth to put them a bit more separated.
template<typename _Tp>
int Class_name::general_function(_Tp);
I think it should do as a style intro.
If you use inheritance, for the java-style working, mark every function except the constructors virtual so that the #overrides behave correctly.
What you have written in the above code is a correct syntax . If you are looking for a thumb rule, code your acccessor functions in such a way that they are set / get exactly the values .
EG :
void SetMyAge(int newAge)
{
if(newAge > 10 && newAge < 100)
_age = newAge ;
}
I would prefer to put the validation "newAge > 10 && newAge < 100" in a different function, IsValidAge ; even if the code is just one line. On the long run, small functions help in maintaining the code, and helps new developers to understand the code better.
void SetMyAge(int newAge)
{
if(IsValidAge() )
_age = newAge ;
}
However I would like to comment on this
void SetMyAge(int myAge){
this->myAge = myAge;
}
It is good practice to differentiate the nameing convention of the class varaiable to _myAge .
EDIT
I think the variable name was comprehended improperly .
myAge should be named _myAge .