It'd be convenient to just update a private member variable whenever I
wanted without having to declare a new object every time. Is this possible?
Thanks for any response.
///Playing with inheritance and other stuff
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>
usingnamespace std;
class yeehaw
{
private:
int ketchup;
protected:
string kong;///* try to access this directly from child class *
public:
yeehaw()
{
ketchup = 0;
}
yeehaw(int a) : ketchup(a) {} ///New notation
void printKetchup() { cout<<ketchup<<endl; }
};
int main()
{
yeehaw yoshi;
cout<<"Before initializing ketchup to 25: ";
yoshi.printKetchup();
///will not let me initialize constructor to a new value w/out declaring new object
yeehaw mcdouble(25);
cout<<"After initializing ketchup to 25: ";
mcdouble.printKetchup();
return 0;
}
I just tried to play with but I don't get it Vlad. Is the yeehaw function you specified a constructor. How would I call it?..looking up operator now...
Since the constructor is non-explicit, this will compile even without operator=.
Without an appropriate operator=, when you write yoshi = 25;
It's as if you had written: yoshi = yeehaw(25);
In other words, you still create a new (temporary) object every time.
You've misunderstood. I meant the public function in the yeehaw class:
1 2 3 4 5
yeehaw & operator =( int red )
{
ketchup = red;
return ( *this );
}
The program compiled fine and yoshi was updated just fine without the function. I don't know how to do it without the equal operator you just showed me. I played around with that function and couldn't figure out for the life of me what it did...could you shed some light on it?
@Athar. That was my initial problem. After I declared an object from yeehaw: yeehaw yoshi(25), it wouldn't let me do it again
No, you did. I explained why it works without operator=(int).
The compiler provides an assignment operator that allows you to assign a yeehaw object to another yeehaw object automatically, in case you were not aware.
I don't know how to do it without the equal operator
It's the assignment (copy) operator, not equal operator.
Normally, to change a private member, you use a setter: void setKetchup(int newKetchup) {ketchup=newKetchup;}
In order to avoid accidental conversions, you should make constructors with one parameter explicit: explicit yeehaw(int a) : ketchup(a) {}
edit: @athar...Thanks. Honestly this concept is still murky.
I will use a setter like you said earlier but just to clarify....The only way I know how
to update a private member variable via a constructor is when you initially declare
an object and initialize a value:
yeehaw yoshi(42);
and how Vlad from moscow just showed me:
yoshi = 42;
So the equal operator does nothing? When I tried to update the private variable like
this: