0

Lets suppose I have the following example struct with a constructor

struct CAddition {
    int x;
    int y;
    int c;
    int result() { 
        return x + y; 
    }
    CAddition();
    ~CAddition();
};

CAddition::CAddition()
    :x(0)
    ,y(0)
{
    c = result();
}

Now if want to initialize c in the above way it works, but what if I want to initialize my c in within the initialization list something like

, c(result())

it shows a correct result somehow, but is it a correct syntax ? can I face some problems?

Novice_Developer
  • 1,432
  • 2
  • 19
  • 33
  • That's C++, not C -- fixed it for you. –  May 03 '18 at 09:12
  • sorry I clicked on the tag quickly , thanks :) – Novice_Developer May 03 '18 at 09:13
  • *"it shows a correct result somehow"* - Why shouldn't it? – StoryTeller - Unslander Monica May 03 '18 at 09:14
  • As long as `c` is initialised (which really means declared) after any other members `result()` uses, why would there ever be a problem? Methods themselves do not need initialised; whether they are valid to use during initialisation only depends on whether/which members they need to access (well, if they're not virtual, that is...) – underscore_d May 03 '18 at 09:14
  • @StoryTeller i tried it for a simple example but the code which i have has big nested structures for which i am creating new constructors , thought if there is a possibility it would break the code if this syntax is wrong – Novice_Developer May 03 '18 at 09:16
  • 1
    @Robert - The syntax isn't wrong (or it wouldn't even build). There is a possible problem that may happen, but compilers are good at warning you about it: http://coliru.stacked-crooked.com/a/a60d298e1394d91f – StoryTeller - Unslander Monica May 03 '18 at 09:18

0 Answers0