Monday, December 18, 2017

Initializers

In C++, classes and sructs have few differences. Structs have public access as the default (just like in C) and classes have private access as default. Both allow for curly braces initialization. Curly braces are preferred except where the auto keyword is used as the type.
#include <iostream>
using namespace std;

struct S {
  int x, y;
  string mystr {"hello world"};   // curly brace initializer
  S(int j, int k)                 // "normal" constructor
  {
    x=j;
    y=k;
  }
  S():x(0),y(0){}                 // constructor with initializer
};

class C : public S {              // class C inherits from struct S
  public:
    int z{9};
    C(int a, int b, int c):S(a,b) // subclass & super class constructors
    {
      z = c;
    };
    C(int j):S(3, 4)              // super class constructor passed 3 and 4
    {
      z=j;
    };
    C():S(){};                    // super class constructor will be initialized with zeros
};

int main() {
  C c;
  // printf may cause problems but I wanted to investigate how it can be used
  printf("x=%i, y=%i, z=%i, str=%s\n", c.x, c.y, c.z, c.mystr.c_str());

  C c2(11);
  printf("x=%i, y=%i, z=%i, str=%s\n", c2.x, c2.y, c2.z, c2.mystr.c_str());

  C c3(-1, -2, -3);
  printf("x=%i, y=%i, z=%i, str=%s\n", c3.x, c3.y, c3.z, c3.mystr.c_str());
}
$ g++ -std=c++14 -c -o class_struct.o class_struct.cpp
$ g++ -o class_struct class_struct.o
$ ./class_struct
x=0, y=0, z=9, str=hello world
x=3, y=4, z=11, str=hello world
x=-1, y=-2, z=-3, str=hello world