0

Code as below:

#include <iostream>
#include <cstdio>
using namespace std;

typedef char BYTE;
#define BUF_SIZE 30

class A
{
public:
    A();
    ~A(){}
    inline const BYTE* GetBuffer() const { return m_pBuf; }
    int Pop(void);
private:
    const BYTE* m_pBuf;
};

A::A():m_pBuf() //<---line 19
{
    BYTE* pBuf = new BYTE[BUF_SIZE];
    if (pBuf == NULL)
        return;

    for (int i=0; i<BUF_SIZE; i++)
    {
        pBuf[i] = i;
    }

    m_pBuf = pBuf;
}

int main()
{
    A a;
    const BYTE* pB = a.GetBuffer();
    if (NULL != pB)
    {
        for (int i = 0; i<BUF_SIZE;i++)
            printf("%u", pB[i++]);
    }

    return 0;
}

I am trying to figure out how many kind of initialization list of the C++ constructor provided. And I find a special one above.Can someone please help to explain line 19. don't know what does that mean. thx in advance.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
ponypaver
  • 397
  • 1
  • 2
  • 14
  • 1
    Please don't post code snippets with line numbers. If you need to show something on a specific line add a comment in the code instead. – Some programmer dude Sep 21 '15 at 09:35
  • Sorry, what's the question? – Kerrek SB Sep 21 '15 at 09:36
  • This code is bogus voodoo. `new BYTE[BUF_SIZE]` cannot return null. The code is equivalent to `A() : m_pBuf(new BYTE[BUF_SIZE]{0, 1, ..., 29}{}` – Kerrek SB Sep 21 '15 at 09:37
  • As for your problem, what is it you wonder about initialization lists? – Some programmer dude Sep 21 '15 at 09:37
  • And on an unrelated note, if you have buffer that is fixed in size at time of compilation (`BUF_SIZE` is a compile-time constant) you should consider using [`std::array`](http://en.cppreference.com/w/cpp/container/array) instead, or at the very least just declare it as an array to begin with. There's really no need for a pointer here. – Some programmer dude Sep 21 '15 at 09:38
  • 1
    @JoachimPileborg: That would depend on your platforms stack space constraints, wouldn't it? That'd be a terrible idea when you're programming for the Palm. – Kerrek SB Sep 21 '15 at 09:39
  • My question is: how could you initialize a char pointer like A::A():m_pBuf(), If m_pBuf is a object, then, I could understand it's calling the default constructor with code: A::A():m_pBuf(). – ponypaver Sep 22 '15 at 05:25

1 Answers1

0

A::A() is calling a constructor of A. And operator : is initialization list, which tells to call default constructor on A's private member m_pBuf.

DawidPi
  • 2,285
  • 2
  • 19
  • 41