I have a logic in base class constructor. The result of the logic has to be captured in the derived class constructor in a temporary variable. Is there a way to do it?
For example
class Base
{
Base() { int temp_value = some_logic; }
};
class Derived : public Base
{
Derived() { // need the temp value here.. }
};
Thanks,
Gokul.
I guess the easiest way I can think of would be to just separate some_logic into it's own method...
class Base
{
Base() { int temp_value = initializationLogic(); }
int initializationLogic(){ return some-logic;}
};
class Derived : public Base
{
Derived() { int temp_value_here_too = initializationLogic(); }
};
Either:
class Base
{
protected int not_so_temp_value;
Base() { not_so_temp_value = some_logic_result; }
};
class Derived : public Base
{
Derived() { // read the not_so_temp_value member here.. }
};
Or:
class Base
{
Base(int some_logic_result) { int temp_value = some_logic; }
};
class Derived : public Base
{
static Derived* create()
{
int some_logic_result = some_logic;
return new Derived(some_logic_result);
}
Derived(int some_logic_result) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
This is the one i am planning to use
class Base
{
Base(int& some_logic_result) { some_logic_result = some_logic; }
};
class Derived : public Base
{
Derived(int some_logic_result = 0) : Base(some_logic_result)
{ // use the some_logic_result here.. }
};
Thanks,
Gokul.
Related
I learn C++ OOP-paradigm and want to ask related question:
Assumption
We have a base class:
class Base {
public:
virtual SomeType PowerMethod() { return SomeType{} };
}
We have a variable target and subclass which realizes some calculations with target variable based on the constructor's parameter (simple calculations or complicated calcs):
class Calc : public Base {
public: // using only public access to simplify real code structure
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
Question
How to optimally realize two classes which based on different methods (Simple or Complex) but provide the same functionality of PowerMethod()?
My solution
class SimpleCalc : public Calc {
bool isSimple = true;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
class ComplexCalc : public Calc {
bool isSimple = false;
public:
SomeType PowerMethod() override {
Calc CalcInstance(isSimple);
return CalcInstance.target;
};
};
This solution is pretty "ugly" and I want to ask you how to make it more readable.
Thank you!
I think that in your code, you didn't mean to craete a new Calc object, but instead call it on the superclass. This can be done like so:
Calc::Simple();
You can override the method PowerMethod, but still call the superclass's code:
virtual SomeType PowerMethod() override {
//do something
Base::PowerMethod();
}
If your problem is more complicated, and polymorphism and superclasses can't help you, you can always declare some method protected, so that only subclasses can access it. So, you could for example do this:
class Calc : public Base {
protected:
SomeType target;
void Simple() { target = 1; };
void Complex(){ target = 10000; };
public:
explicit Calc(bool isSimple) {
if(isSimple)
Simple();
else
Complex();
}
};
class SimpleCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Simple();
return Calc::target;
};
};
class ComplexCalc : public Calc {
public:
SomeType PowerMethod() override {
Calc::Complex();
return Calc::target;
};
};
If your target is to learn OOP then you can use a factory design pattern to create your final calculator based on isSimple condition:
#include <iostream>
class Base
{
public:
Base()
{
target = 0;
}
int target;
virtual void PowerMethod() = 0;
};
class SimpleCalc : public Base
{
virtual void PowerMethod() { target = 0; }
};
class ComplexCalc : public Base
{
virtual void PowerMethod() { target = 1000; }
};
class CalcFactory
{
public:
virtual Base* createCalc(bool isSimple)
{
if (isSimple)
return new SimpleCalc();
else
return new ComplexCalc();
}
};
int main()
{
CalcFactory factory;
Base * base1 = factory.createCalc(true);
Base * base2 = factory.createCalc(false);
base1->PowerMethod();
base2->PowerMethod();
std::cout << base1->target << std::endl;
std::cout << base2->target << std::endl;
}
I have a class Base and another class Derived (derived from Base).
Also I have a 2 functions GetValue(Base*) and GetDerivedValue(Derived*).
Now, from the main() function, I have access to only GetValue(), but I need the value of both Base and Derived classes.
class Base
{
public:
Base ()
{
abc =0;
}
~Base ()
{
abc =0;
}
int abc;
};
class Derived : public Base
{
public:
Derived ()
{
def =0;
}
~Derived ()
{
def =0 ;
}
int def;
};
int GetDerivedValue (int &def)
{
def = 5;
}
int GetValue (Base *&pbase)
{
Derived *d = new Derived ();
GetDerivedValue (d->def);
pbase = (Base *) d;
}
int main ()
{
Base *pbase = NULL;
GetValue (pbase);
// Goal here is to get the avlue of def as 5 without any memory issue
}
Where should I release the pointers to make sure there is no memory errors?
I think you are looking for something like this:
class Base
{
public:
Base() : abc(0) {}
virtual ~Base() {}
int abc;
};
class Derived : public Base
{
public:
Derived() : def(0) {}
~Derived() {}
int def;
};
void GetDerivedValue(int &def)
{
def = 5;
}
void GetValue(Base* &pbase)
{
Derived *d = new Derived;
GetDerivedValue(d->def);
pbase = d;
}
int main()
{
Base *pbase = NULL;
GetValue(pbase);
// use pbase as needed...
delete pbase;
}
Which would be better written using std::unique_ptr instead:
#include <memory>
class Base
{
public:
virtual ~Base() = default;
int abc = 0;
};
class Derived : public Base
{
public:
int def = 0;
};
void GetDerivedValue(int &def)
{
def = 5;
}
std::unique_ptr<Base> GetValue()
{
auto d = std::make_unique<Derived>();
GetDerivedValue(d->def);
return d;
}
int main()
{
auto pbase = GetValue();
// use pbase as needed...
}
I have a class hierarchy like:
class A {
list<A*> children;
public:
void update() {
do_something();
update_current();
for(auto child : children)
children->update();
}
protected:
virtual void update_current() {};
};
class B : public A {
protected:
void update_current() override {
do_something_important();
};
};
class C1 : public B {
protected:
void update_current() override {
B::update_current();
do_something_very_important();
};
};
class C2 : public B {
protected:
void update_current() override {
B::update_current();
do_something_very_important_2();
};
};
int main() {
A* a = new A();
//fill a's childred list somehow
while(come_condition) {
//some code
a.update();
//something else
}
return 0;
}
The question is: how can I remove duplicate B::update_current(); calls from derived classes without changing program's behaviour? Is it possible or are there no solutions except calling base class functions manually? Thank you.
You could make B's children override a different function:
class B : public A {
protected:
void update_current() override final {
do_something_important();
do_something_important_later();
};
virtual void do_something_important_later() = 0;
};
With:
class C2 : public B {
protected:
void do_something_important_later() override {
do_something_very_important_2();
};
};
class Base{
protected:
int remainItems = 0;
public:
Base(){}
virtual int numOfItem() = 0;
};
class Deveried1 : public Base{
public:
Deveried1() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 5;
}
};
class Deveried2 : public Base{
public:
Deveried2() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 10;
}
};
class Deveried3 : public Base{
public:
Deveried3() :Base(){ remainItems = numOfItem(); }
int numOfItem(){
return 10;
}
};
int main(){
Base* foo = new Deveried3;
}
With this design, for every deveried class, I must do the same thing in constructor to initalize remainItems. I'd like to know if there are some better way/pattern in this situation.
Indeed, you can't call derived class functions from the base class constructor, so this kind of twisted inversion of dependencies can't work. I'd pass the value to the base-class constructor:
Base(int numOfItems) : remainItems(nomOfItems) {}
Derived1() : Base(5) {}
Derived2() : Base(10) {}
I do not see any benefit in the method, so I removed it and added an option to pass the variable in the base class constructor:
class Base{
protected:
int remainItems;
public:
Base(remainItems = 0) { this->remainItems = remainItems; }
};
class Deveried1 : public Base{
public:
Deveried1() :Base(5){}
}
};
class Deveried2 : public Base{
public:
Deveried2() :Base(10){}
}
};
class Deveried3 : public Base{
public:
Deveried3() :Base(10){}
}
};
int main(){
Base* foo = new Deveried3;
}
I believe what you're looking for is called the Non-Virtual Interface pattern.
How to implement an interface class using the non-virtual interface idiom in C++?
I want to call a method from A class in constructor of other class
I googled, but did not find any answer
For example, I have :
class A{
void doWork();
}
class B{
B(){
//here i want to have doWork method
}
}
You told us not enough to choose proper solution. Everything depends on what you are trying to achieve. A few solutions:
a) Mark A method as static.
class A
{
public:
static void DoSth()
{
// Cannot access non-static A members here!
}
};
class B
{
public:
B()
{
A::DoSth();
}
};
b) You can instantiate A in place
class A
{
public:
void DoSth()
{
// Do something
}
};
class B
{
public:
B()
{
A a;
a.DoSth();
}
};
c) You can put A's instance into B:
// A remains as in b)
class B
{
private:
A a;
// or: A * a;
public:
B()
{
a.DoSth();
// or: a = new A; a->DoSth();
// Remember to free a somewhere
// (probably in destructor)
}
}
d) You may derive B from A:
class A
{
protected:
void DoSth()
{
}
};
class B : public A
{
public:
B()
{
DoSth();
}
};
e) You can forget about A class and make DoSth a function:
void DoSth()
{
// ...
}
class B
{
public:
B()
{
DoSth();
}
}
Since you provided not enough data, you have to choose solution on your own.
In order for that to work you'd need to subclass it.
So it'd be like this:
class A {
doWork();
}
class B : A {
B(){
doWork();
}
}
You could also do it like so going for a HAS-A rather than IS-A relationship:
class A {
doWork();
}
class B {
A myA;
B(){
myA.doWork();
}
}
Without knowing more of what you are doing I'd go with the top (IS-A) solution which is what I think you are trying to do.
Or
class A
{
public:
static void doWork();
};
class B
{
B(void)
{
A::doWork();
}
};
?
PS: Here B::B() will be private