0

I have been working through C++. I am struggling to get my head round the member initialization, particularly one line of code. Consider the following program;

#include <iostream>
#include <cstdint>

class RGBA
{
private:
    uint8_t m_red = 0;
    uint8_t m_green = 0;
    uint8_t m_blue = 0;
    uint8_t m_alpha = 255;



public:
    ***RGBA(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255):
        m_red(red), m_green(green), m_blue(blue), m_alpha(alpha)***
    {
    }

    void print()
    {
        std::cout << "r = " << static_cast<int>(m_red) << " g = " << static_cast<int>(m_green) << " b = " << static_cast<int>(m_blue) << " a = " << static_cast<int>(m_alpha) << '\n';
    }
};

I have bolded the line of code I am having problems with ( the first declaration in 'public' My question is, why do I have to declare alpha to be 255 when I dont have to declare red green or blue as 0, whereas I have to declare them all in the private section.

Could someone please explain this to me, and even better explain this concept of member initialization. Thank you, any help is much appreciated.

int main()
{
    RGBA teal(0, 127, 127);
    teal.print();

    return 0;
}
FrankWhite
  • 97
  • 1
  • 3
  • 11
  • `255` is a default argument for `alpha`, so you don't have to do `RGBA(R, G, B, 255)` every time you want a fully opaque color. You can do `RGBA(R, G, B)`. – LogicStuff Jan 06 '16 at 12:31

1 Answers1

1

RGBA, The A component is for alpha, and it is transparency. If you have it as 0, your image or whatever would be fully transparent/invisible. Having it on 255 (max) means RGB colors won't be affected.

Tarik Neaj
  • 548
  • 2
  • 10
  • Thanks Tarik! I understand that point, but in context of the small program, why do we not have to say red = 0, green = 0 and blue =0 ? is it because by default they are set to zero? thanks, Frank! – FrankWhite Jan 06 '16 at 12:29
  • 1
    Sorry I misunderstood the question, the reason you don't have to set them to 0 is because the user determines their value. You want alpha to be 255 and the user has no control of it. In your main, you call the function with your own RGB values. – Tarik Neaj Jan 06 '16 at 12:30
  • right ok, I am still struggling a little. In the private part of the class, we initialize our variables to 0, 0, 0, 255. I understand this. However now in the public part, inthe member initialization, why dont we say 'uint8_t red = 0, uint8_t green = 0 ..... ' instead we dont do anything with these, but we do say uint8_t alpha = 255. Thanks again Tarik, I will get it soon :) – FrankWhite Jan 06 '16 at 12:33
  • Well, that part of your code (alpha part) is not needed at all and can be removed. You already initialize alpha to 255 so there is no need to have it in the function. – Tarik Neaj Jan 06 '16 at 12:34
  • I thought so, for that line I could have; RGBA() : m_red(red), m_green(green), m_blue(blue), m_alpha(alpha) and this would suffice, thanks Tarik :) – FrankWhite Jan 06 '16 at 12:39