3

Is it possible to specify alignment of parent class? for example something like (which does not compiled):

template<size_t n>
class Vector : public boost::array<double,n> __attribute__ ((aligned(16)))
{

thanks

well, from comments I gather this is no good way to go. I think I will just stick to composition/alignment of private array

Anycorn
  • 50,217
  • 42
  • 167
  • 261
  • Why do you want to do this? (and, in this instance, you should use composition instead of inheritance). โ€“ James McNellis May 01 '10 at 17:33
  • @James I do use composition now, but want to remove wrapper boilerplate. โ€“ Anycorn May 01 '10 at 18:18
  • 2
    you really wont want to do that in the long run. It saves you a bit of typing now but at the cost of opening your class to a world of subtle bugs if it is ever misused. Using inheritance in this way is a very fragile design. At very least use private inheritance, http://stackoverflow.com/questions/656224/when-should-i-use-c-private-inheritance/675451#675451 is an example of how to do it. In the end you'll be happier if you just stick with composition. โ€“ deft_code May 01 '10 at 20:53

2 Answers2

5

We don't need to request alignment on the derived class neither we can. The reason why we don't need is that it is enough to request alignment for the derived class, and that requesting alignment to the derived class will result on layout for the base class that depends on the derived.

class A : public C __attribute__ ((aligned(16)))
{


class B : public C __attribute__ ((aligned(8)))
{

Which will be alignment for C?

Vicente Botet Escriba
  • 4,305
  • 1
  • 25
  • 39
2

GCC guarantees that the first base class is at offset zero within the derived class layout. Therefore it's sufficient in this case to align the derived object.

I can't find a good reference at the moment but see here under -wABI, where they describe an exception to the unstated rule: if the base is empty, it may not be at offset zero.

I suppose there would be another exception if the first base lacks a vtable but the derived object has one. array falling into that category, I'd watch out. Of course, the standard leaves layout unspecified: ยง10/3.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421