Overview
Examples
Screenshots
Comparisons
Applications
Download
Documentation
Tutorials
Bazaar
Status & Roadmap
FAQ
Authors & License
Forums
Funding Ultimate++
Search on this site
Search in forums












SourceForge.net Logo
Home » Community » Newbie corner » Order of member initialization
Re: Order of member initialization [message #58872 is a reply to message #58871] Tue, 20 September 2022 18:27 Go to previous messageGo to previous message
jjacksonRIAB is currently offline  jjacksonRIAB
Messages: 220
Registered: June 2011
Experienced Member
Quote:

I cannot discuss this, multiple inheritance is too advanced for me.


I hear you. Laughing

It got even crazier than that though. I realized I could also combine it with variadic templates and came up with this monstrosity:

#include <iostream>

using namespace std;

struct BaseA {
   int a { 100 };
   int b { 200 };
   int c { 300 };

   auto& BaseARef() { return *this; }
};

struct BaseB {
   BaseA& baseA;
   
   BaseB(BaseA& baseA) : baseA(baseA) {
       std::cout << baseA.a << "\n";
   }
};

struct BaseC {
   BaseA& baseA;

   BaseC(BaseA& baseA) : baseA(baseA) {
       std::cout << baseA.b << "\n";
   }
};

struct BaseD {
   BaseA& baseA;

   BaseD(BaseA& baseA) : baseA(baseA) {
       std::cout << baseA.c << "\n";
   }
};

template<typename ...Args>
struct Whatever : BaseA, Args... {
   Whatever() : Args(BaseARef())... {}
};

using Test = Whatever<BaseB, BaseC, BaseD>;

int main(void) {
    Test whatever;
}


which prints:

100
200
300


I mean it's kind of neat because you can use one struct as a data holder for the other ones that all of them have access to but I'm unsure whether I'd use it in production code. The other thing that's cool about it is you can kind of change the initialization order by swapping their positions around in the using statement:

using Test = Whatever<BaseD, BaseC, BaseB>;


prints

300
200
100


instead

[Updated on: Tue, 20 September 2022 18:32]

Report message to a moderator

 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: Can TheIDE be used in two instances?
Next Topic: Some Questions
Goto Forum:
  


Current Time: Wed May 08 13:02:28 CEST 2024

Total time taken to generate the page: 0.02003 seconds