Setters and getters across multiple classes? CPP - c++

I'm having some trouble on my homework trying to figure out how I can use a setter function from my base class in a derived class. I'm not sure if I worded that correctly as I'm new to C++, but hopefully my code can explain it better!
class account{
private:
double balance;
protected:
int numwithdraws = 0;
public:
void Setbalance(int bal)
{
balance = bal + balance;
}
int Getbalance()
{
return balance;
}
};
class checking : public account {
public:
WriteCheck(int checknum,double amount)
{
cout<<"Check amount?"<<endl;
cin>>amount;
Setbalance(amount);
checknum++;
}
};
Inside my main function there's an option to make a withdrawal, usually that would mean my balance would go down so I'd have to figure out how to make this negative in my setbalance later, but
checking obj2;
obj2.WriteCheck(0,0);
cout<<"New Balance = "<<obj1.Getbalance()<<endl;
I took out a lot my code to narrow down where the problem point is, but I'll try to explain it better in words if what I wrote down for my code is confusing.
What I have in my base class account are a Setbalance and a Getbalance. In my derived class checking I'm trying to use the Setbalance function that's in my base class in my derived class function WriteCheck to change the amount of my private variable balance which is in my account base class.
The problem is when I use the Setbalance in my derived class function and call my Getbalance in main, it still ends up 0 and doesn't change the amount in variable balance.
I'm getting confused reading my own explanation, so I understand if it's hard to grasp what I'm trying to ask. If that's the case, please let me know so that I can try and explain further!

You're on the right track with what you're trying to achieve (calling a function in the base class from within the derived class). A derived class will generally have the functions that the base class has, so calling
checking obj2;
obj2.Getbalance()
Is perfectly fine. I made some syntax changes to your code so it can run. The only major change I made was set balance to 0 so there wouldn't be any undefined behavior.
#include <iostream>
using namespace std;
class account {
private:
double balance = 0;
protected:
int numwithdraws = 0;
public:
void Setbalance(int bal)
{
balance = bal + balance;
}
int Getbalance()
{
return balance;
}
};
class checking : public account
{
public:
void WriteCheck(int checknum, double amount)
{
cout << "Check amount?" << endl;
cin >> amount;
Setbalance(amount);
checknum++;
}
};
int main()
{
checking obj2;
cout << "New Balance = " << obj2.Getbalance() << endl;
return 0;
}

Related

Derived Get/Set Methods

Imagine I have this code:
class A {
public:
void GetInt() { cout << number << endl; }
void SetInt(int n) { number = n; }
private:
int number = 0;
};
class B : public A {
public:
void GetInt() { cout << number << endl; }
private:
int number = 0;
};
int main() {
B b;
b.SetInt(5);
b.GetInt(); // Prints 0, needs to be 5
return 0;
}
Is there any way to make SetInt() changing B.number without implementing it in B? Imagine I have 500 derived classes from A, and they set their number in the same { number = n; }. Do I have to implement the same SetInt() method 500 times?
The simple way to get what you ask for is this:
class A {
public:
void GetInt() { cout << number << endl; }
void SetInt(int n) { number = n; }
private:
int number = 0;
};
class B : public A {
// don't hide methods inherited from A
// don't add members that are already present (as private member of A)
};
int main() {
B b;
b.SetInt(5);
b.GetInt(); // Prints 5
return 0;
}
Private members are inherited, they just cannot be accessed directly. Though as A does provide public accessors, B has acess to A::number via the setter from A.
PS A method called Get___ should actually return something, not just print the value on the screen.
No, 0 is the correct result. In your class B you create a whole new member B::number which is independent from A:::number. So when you run A::SetInt, that member function changes A::number and when you run B::GetInt, that function accesses A::number which was never set to 5.
Try not to have members in derived types that have the same name as a member in the base class. All it does is create confusion.
In case you really want each derived class to yield and handle its own value in terms of class hierachy separation - which I'd find at least questionable at all in terms of design and problem solution approach - you cannot avoid a minimum amount of code duplication for each derivation. At least you need the member access itself to be duplicated. There are some template/macro tricks to circumvent code explosions here (generic member instrusion), but since I really don't think, that this is what you want to achieve, I do not go into details for now.
Otherwise, idclev 463035818's answer is the way to go.

Derived class inherited getter, can't find a way to return the correct value

I'm trying to have the derived class (Hero) inherit the code for a getter function from the base class (Entity). However, I can't find out how to access Hero's private variables (the correct values) through this getter.
I'm planning on assigning similar getters (about 10 total) to the Hero class as well as another derived class (Enemy). While I can technically write out each getter for the two classes, I rather limit code duplication. Is there anyway I can write the code in Entity and have the two derived classes inherit it?
#include <iostream>
using namespace std;
class Entity{
public:
Entity() {
this->speed = 0;
}
short getSpeed() {
return this->speed;
}
private:
string name;
short speed;
};
class Hero : public Entity{
public:
Hero(short speed) {
this->speed = speed;
}
private:
short speed;
};
int main()
{
Hero hero1(2);
cout << hero1.getSpeed() << endl;
return 0;
}
The output gives me 0, which is the default value of entity. Is there any way to access the hero1 value of 2 and output it?
Why would you want a method of the base return a value that is private to derived? Thats not something that you usually do.
Step back and think what you actually want to achieve. If every Enitity has a speed member and if every Hero is an Entity then Hero needs no private speed in addition.
Instead Hero should initialize its Entity part in the constructor:
class Entity{
public:
Entity(short speed = 0) : speed(speed) {} // <- fixed constructor
short getSpeed() { return speed; }
void setSpeed(short s) { speed = s; }
private:
short speed;
};
class Hero : public Entity{
public:
Hero(short speed) : Entity(speed) {}
};
I changed Entitys constructor such that you can pass an initial value for speed. Then Heros constructor can properly initialize its Entity subobject.
Is there any way to access the hero1 value of 2 and output it?
If you really want speed to be a private member of Hero then you should implement the getter in Hero also, just as you did it for Entity. However, having a speed in both classes and a getter for both is kinda weird. Choose whether speed belongs to Entity or to Hero, very unlikely you need it in both.
One question you should have answered before writing code is: Who is reponsible for what?
In the above example Entity is responsible for managing its speed. We can turn this around by saying: Entity only needs a way to retrieve the speed. How this is actually done is buisness of the subclasses (think of wooden chair vs elven archer wearing boots of speed +5). In code that would be
struct Entity{
virtual short getSpeed() { return 0; }
};
I cannot explain better than others did already, so I quote from cppreference:
Virtual functions are member functions whose behavior can be
overridden in derived classes. As opposed to non-virtual functions,
the overridden behavior is preserved even if there is no compile-time
information about the actual type of the class. If a derived class is
handled using pointer or reference to the base class, a call to an
overridden virtual function would invoke the behavior defined in the
derived class. [...]
TL;DR: virtual enables dynamic dispatch with pointers and references. It encourages subclasses to override the method with their own implementation.
Now subclasses can either be fine with the default implementation (wooden chair) or provide their own:
struct ElvenArcher : Entity {
bool hasBootsOfSpeed = true;
short baseSpeed = 10;
short getSpeed() override {
return hasBootsOfSpeed ? (baseSpeed+5) : baseSpeed;
}
};
Here override declares that the method overrides one in a base class.
PS: Note that I put the important part in bold. It is not clear from your question what would be the correct way to write your code and this answer was mainly born from a comment that was too long for a comment. I tried to outline two extremes. What you actually need is probably somewhere in between.
You need to implement getSpeed in the hero class since speed is a private variable
Here is your corrected code:
#include <iostream>
using namespace std;
class Entity{
public:
Entity() {
this->speed = 0;
}
short getSpeed() {
return this->speed;
}
private:
string name;
short speed;
};
class Hero : public Entity{
public:
Hero(short speed) {
this->speed = speed;
}
short getSpeed() {
return this->speed;
}
private:
short speed;
};
int main()
{
Hero hero1(2);
cout << hero1.getSpeed() << endl;
return 0;
}
Probably it is better to use protected instead
#include <iostream>
using namespace std;
class Entity{
public:
Entity() {
this->speed = 0;
}
short getSpeed() {
return this->speed;
}
protected:
string name;
short speed;
};
class Hero : public Entity{
public:
Hero(short speed) {
this->speed = speed;
}
};
int main()
{
Hero hero1(2);
cout << hero1.getSpeed() << endl;
return 0;
}

How do I modify a private variable in a base class with a derived member function?

My full question because I couldn't fit it all on the title is:how 2 modify a private variable in the base class with a derived class B member function that will call a member function thats been overrided in the base class A which will also modify a different private member variable in the derived class B. I'm having a really tough time trying to figure this out because I can't figure out how to modify two private member variables that are in different classes in two member functions that come from different classes. This is what I have for my code so far. I'll make comments in the code on the issue i'm trying to solve
In my .h file I have:
#include <iostream>
#include <string>
using namespace std;
class A{
public:
A();
A(string name_holder, double balance_holder);
int take(float amount);
string getName();
double getBalance();
void output();
private:
string name;
double balance;
};
class B:public A{
public:
B();
B(int number_of_withdrawal_holder);
int take(float amount);//overriding
void output();
private:
static int count;
};
In my .cpp file I have
#include "Header.h"
A::A()
{
name=" ";
balance=0;
}
A::A(string name_holder,double balance_holder)
{
name=name_holder;
balance=balance_holder;
}
int A::take(float amount)
{
if (balance >= amount && amount>=0)//if the amount is less than or equal to the balance and is nonnegative
{
balance-=amount;
cout<<"ok"<<endl;
return 0;
}
cout <<"Insufficient funds for the withdrawal to take place"<<endl;
return 1;
}
string A::getName()
{
return name;
}
double A::getBalance()
{
return balance;
}
void A::output()
{
cout<<"Name: "<<getName()<<endl;
cout<<"Balance: "<<getBalance()<<endl;
}
int B::count=0;
B::B()
{
count=0;
}
B::B(int number_of_withdrawal_holder)
{
count=number_of_withdrawal_holder;
}
int B::take(float amount)
{
if(count==0)//if this is the first withdrawal
{
++count;
return BankAccount::take(amount);
}
//the bottom part of the code gets excuted if you already withdrew atleast once-you pay a fee of 1.50(in other words i want to do a function call to the first withdraw function and subtract 1.50 from the member variable balance but I also want to modify count in the base class function take
++number_of_withdrawals;
return BankAccount::withdraw(amount);
}
If anyone can help me out that would be great!
A private member is private even to derived subclasses. If you want to allow a derived subclass to access a member, make it protected instead of private. Such members are still not public, but can be accessed by subclasses.
Moved to an answer:
I think you doing it wrong.. your base class is an account which provides you sort of interface to transactions for a specified account, so you shouldn't to modify any internals of the base class rather then what's provided by a public interface, so your 'fee' is also a withdraw operation..
As also truly mentioned in comments, A::take() should be declared virtual
class A {
...
virtual int take(float amount);
...
}
class B: public A {
B() {
m_nNumberOfWithdraw = 0;
}
B::B(int number_of_withdrawal_holder) {
m_nNumberOfWithdraw =number_of_withdrawal_holder;
}
int B::take(float amount) {
int nResult = A::take(m_nNumberOfWithdraw > 0 ? amount + 1.50 :amount);
if (nResult == 0)
m_nNumberOfWithdraw++;
return nResult;
}
protected:
int m_nNumberOfWithdraw;
};

Inherited 'Get' function will not return correct value

I have a base class BankAccount, then 3 derived classes: SavingsAccount, CheckingAccount, and AchieverAccount(also inheriting checking). The only get_ function is in the base class public. When I call it from the 3 derived classes it returns 0, which I assume is that base class's constructor's doing. I made the getBalance function with this->balance(); as a test to see if it would return the balance, no luck, I had it as just return balance; before hand. I have tried to make the balance public, even though it isn't a good idea and still nothing. So it has to be that the SavingsAccount isn't inheriting it right, or getBalance isn't getting the right balance, in which can I need help.
I'm not going to include all of the code because it turns out to be a lot, but I'll put it what I think is important, if you want I can put it all in though. This is only for SavingsAccount, because I think if I get help on this I can figure it out elsewhere.
All of these have #include and using namespace std;
BankAccount.h
class BankAccount{
public:
BankAccount();
BankAccount(double amount);
double getBalance();
};
private:
double balance;
BankAccount.cpp
#include "BankAccount.h"
BankAccount::BankAccount(){
balance = 0;
}
BankAccount::BankAccount(double amount){
balance = amount;
}
double BankAccount::getBalance(){
return this->balance;
}
SavingsAccount.h
#include "BankAccount.h"
class SavingsAccount: virtual public BankAccount{
public:
SavingsAccount();
SavingsAccount(double amount);
private:
double balance;
};
SavingsAccount.cpp
#include "SavingsAccount.h"
SavingsAccount::SavingsAccount(){
balance = 0.00;
}
SavingsAccount::SavingsAccount(double amount){
balance = amount;
interest = .09;
}
Main.cpp
#include "SavingsAccount.h"
#include "BankAccount.h"
void main(){
cout << "Creating new SavingsAccount with $2000.00" << endl;
SavingsAccount sa(2000.00);
cout << "Current balance: $" << sa.getBalance() << endl;
}
Output
Creating new SavingsAccount with $2000.00
Current balance: $0.00
Press any key to continue . . .
BankAccount class very likely has a member named balance (not shown in your code for some reason) - otherwise BankAccount(double) constructor wouldn't compile.
SavingsAccount class also has a member named balance. Realize that SavingsAccount::balance is distinct from and unrelated to BankAccount::balance. SavingsAccount's constructor initializes the former, while BankAccount::getBalance returns the value of the latter.
You are probably looking for something like this:
class BankAccount {
double balance;
public:
BankAccount(double value) : balance(value) {}
double getBalance() const { return balance; }
};
class SavingsAccount : public BankAccount {
public:
SavingsAccount(double value) : BankAccount(value) {}
};
I suggest you read about constructor initializer lists in your favorite C++ textbook.
I do not see a balance variable declared for the base class yet you refer to it.. how is this working? I assume you have one and just did not copy it in here..
However the issue is your savings account declares a balance as well which would get set to 2000. but your getBalance defined in your parent class cannot see that value and return 0.
Do you want to have a single savings variable for each account? In that case, you should not redefine savings in the derived class. You are calling the get in the base class and getting 0 returned.

Defining two classes inside a class, and accessing its members

I'm trying to access members of a classC from classB, both classC and classB are inside classA. Here is what I'm trying to do;
//hello.h
class hello{
public:
hello();
class letters{
public:
letters();
void setName(char n);
char getName();
private:
char name;
}
class sayHi{
public:
sayHi();
void onJoin();
}
}
//hello.cpp
hello::hello(){}
hello::letters(){}
hello::sayHi(){}
void hello::letters::setName(char n){
hello::letters::name = n; //trying to access the private variable 'name' inside class letters
}
char hello::letters::getName(){
return hello::letters::name = n;
}
void hello::sayHi::onJoin(){
cout<< hello::letters::getName() <<endl;
}
I know i'm doing it wrong, am I supposed to create instances of each class and call the members?
Yes, you're supposed to create instances of the classes.
These are frequently called "objects", which is why they call it "object-oriented programming".
First, your getName and setName should look like this:
void hello::letters::setName(char n) {
name = n;
}
char hello::letters::getName() const { // Declaration should also say "const".
return name;
}
With that out of the way, any sayHi instance needs to know which letters to say "Hi" to, which means that you need to tell it.
This is usually done by passing a parameter to the method that needs to know:
class sayHi{
public:
sayHi();
void onJoin(const letters& who)
{
cout << who.getName() << endl;
}
};
which you would use somewhat like this:
int main()
{
hello::letters letter;
letter.setName('p');
hello::sayHi greeter;
greeter.onJoin(letter);
}
What is the error you are getting ? where have you created objects for accessing these methods ? Also
return hello::letters::name = n;
this line is wrong, it should be
return hello::letters::name;