'C++ Overriding private class attributes
Anyone can advise on how to simply reset a class' private attributes? (referring to int forward and int backwards from within Default class)
What I want to achieve:
Case 1: Use int forward and int backwards with default values VK_UP and VK_DOWN << This is done.
Case 2: I want to be able to reset the default into some other keypress. << ADVICE HERE needed
#include <iostream>
#include <windows.h>
#include <string>
#include<conio.h>
using namespace std;
bool reset_defaults = false;
class Replace_defaults {
public:
void check() {
switch (reset_defaults) {
case true:
cout << ("Now running with reset commands >>>\n");
//// HERE override function ...
break;
}
}
};
// Base class
class Default {
int forward = VK_UP; // << **TO RESET!!**
int backwards = VK_DOWN;
public:
bool standBy = true;
void get_default() {
int new_def = forward;
}
int move() {
while (reset_defaults == false) {
if (GetAsyncKeyState(forward) < 0)
{
cout << ("FORWARDS >>>\n");
if (GetAsyncKeyState(forward) == 0)
{
cout << ("Stopped forwards\n");
}
}
if (GetAsyncKeyState(backwards) < 0)
{
cout << ("BACKWARDS >>>\n");
if (GetAsyncKeyState(backwards) == 0)
{
cout << ("Stopped backwards\n");
}
}
if (GetAsyncKeyState(VK_RIGHT) < 0)
{
reset_defaults = true;
cout << ("RIGHT Key pressed - Stopped \n");
Replace_defaults reset;
reset.check();
}
if (GetAsyncKeyState(VK_SPACE) < 0) { break; }
}
return 0;
}
int accessPrivate() {
return forward;
}
};
class Replace_defaults_overload: public Replace_defaults {
public:
void check() {
switch (reset_defaults) {
case false:
cout << "Default comands running \n";
Default test;
test.move();
}
}
};
int main() {
Replace_defaults_overload replace;
Default def;
replace.check();
return 0;
}
Solution 1:[1]
Having them under the protected access modifier would allow an inherited class to change the values of forward and backward. Otherwise private is only accessible within the parent class
class Default {
protected
int forward = VK_UP; // << **TO RESET!!**
int backwards = VK_DOWN;
public: ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alejandro Perez |
