1

I have the following template:

Tup4.h:

#pragma once
#include <array>
#include "Comparisons.h"

class Tup4Data {
protected:
    std::array<double, 4> v;
};

template <class C>
class Tup4Impl : Tup4Data {
public:
    Tup4Impl<C>(std::array<double, 4> vc) :
        v(vc) {};

    bool equals(const Tup4Impl<C>& t) {
        return fuzzyEquality<4>(v, t.v);
    }

};

Then I have a small program like this:

#include <iostream>
#include "Comparisons.h"
#include <array>
#include "Tup4.h"


class Vec4 : Tup4Impl<Vec4>{};


int main() {
    std::array<double, 4> a1 = {1.0, 1.0, 1.0, 1.0};
    std::array<double, 4> a2 = { 1.0, 1.0, 1.0, 1.0 };
    Tup4Impl<Vec4> v1 = Tup4Impl<Vec4>(a1);
    Tup4Impl<Vec4> v2 = Tup4Impl<Vec4>(a2);
    v1.equals(v2);
}

Running this throws the following error: Error C2614 'Tup4Impl': illegal member initialization: 'v' is not a base or member

Why is this initialization illegal? I can fix this code just by changing the Constructor method to

Tup4Impl<C>(std::array<double, 4> vc){
            v = vc;
}

But I'm curious as to why the initilization is illegal like this

For clarification: the error occurs in Tup4Impl <Vec4>, meaning that the problem is not in the template but in the class that implements it. v is defined as a protected member in the parent class, so it should be a member, right?

  • You might use `Tup4Impl(std::array vc) : Tup4Data{vc} {}`. – Jarod42 Dec 25 '21 at 00:01
  • 1
    *"Why is this initialization illegal?"* Because the C++ language is like that... You can initialize the base, but not part of it. – Jarod42 Dec 25 '21 at 00:02
  • 1
    To initialize base class members you should call base class constructor. – Osyotr Dec 25 '21 at 00:02
  • I understand now, thank you – Francisco José Letterio Dec 25 '21 at 00:13
  • 1
    @FranciscoJoséLetterio You can write an answer to your own question to describe what needs to be changed in the code in your question, and why. That may help others in the future. It doesn't matter that you got the hints from comments to your question. – Ted Lyngmo Dec 25 '21 at 00:17
  • Unrelated to your question, you should stop mentioning the template name `` inside the class. That's become illegal from C++20, so your code will start breaking. It's redundant anyway, so you can get rid of it without any trouble. – cigien Dec 25 '21 at 04:27
  • @cigien so inside the class all references to the class are assumed to be generic? – Francisco José Letterio Dec 25 '21 at 07:01
  • Not in all places, just in constructors and destructors actually. See https://stackoverflow.com/questions/63513984/ – cigien Dec 25 '21 at 07:04

0 Answers0