How to create an instance of a struct in C++?

This is what you need:

Book CreateBook( unsigned int pageNum){

    Book bk = new _book();

    bk->pageNum = pageNum;

    return bk;
}

your bk was null and you cannot access pageNum when the pointer is null.

And don't forget to call delete on bk when you are done using it.


You're assigning bk to NULL and then trying to access a member of it. That's the same as a null pointer in Java, and what you're doing would typically raise a NullPointerException (thanks from the comments). If you want to create a pointer to your struct, you need to use operator new:

bk = new _book;
// ...
return bk;

and then make sure you call delete on the pointer when you're done with it.

I would advise against using pointers here, though. Unlike other languages, C++ lets you create objects by value. It also allows for references and pointers, but only use pointers when you absolutely must. If you simply want to create a book object with a given pageNum, you should create a constructor while you're at it:

struct _book {
    int pageNum;
    _book(int n) : pageNum(n) // Create an object of type _book.
    {
    }
};

and then you can invoke it like

_book myBook(5); // myBook.pageNum == 5

If you're new to C++, please get yourself a good book on it. It's not just a low-level language, and it's also not just an OOP language. It's a multi-paradigm swiss army knife language.

Tags:

C++

Struct