Search code examples
c++ubuntuvisual-c++hdlverilator

How to initialize a class type used as a function parameter


I am trying to get a handle on HDL to C++ conversions and have hit a bit of a snag. The conversion using Verilator on Ubuntu is easy enough but one data type is annoying me.

The top code in the hierarchy is...

#include <iostream>
#include "VDorQ24Syms.h"
#include "VDorQ24.h"

using namespace std;
// FUNCTIONS
VDorQ24Syms::VDorQ24Syms(VDorQ24* topp, const char* namep)
    // Setup locals
    : vm_namep(namep)
    , vm_activity(false)
    , vm_didInit(false)
    // Setup submodule names
{
    // Pointer to top level
    tOPp = topp;
    // Setup each module's pointers to their submodules
    // Setup each module's pointer back to symbol table (for public functions)
    tOPp->Vconfigure(this, true);
    // Setup scope names
}

Passing data to the function

VDorQ24Syms::VDorQ24Syms(VDorQ24* topp, const char* namep)

is what I'm not getting. The second parameter is easy to understand. The first, not so much.

By this I mean, what is the compiler expecting me to pass? Which data type?

I want to pass data like so...

VDorQ24* randomCharacter;
if (VDorQ24Syms(randomCharacter, szAscii) == /*condition*/)
{
    return /*value*/;
}

But 'randomCharacter' is uninitialized.

VDorQ24* randomCharacter = /*How do I initialize this?*/;

Solution

  • You example is not complete, but this might help you.

    Your variable randomCharacter is not an instance of your class VdorQ24, it's a pointer to your class.

    If you want to initialize your variable, set it to nullptr:

    VdorQ24* randomCharacter = nullptr; // now you can be 100% certain that it's null.
    

    If you acually wanted to create a new instance of VdorQ24, you can simply forget about the pointer and use values. Here we call the default constructor:

    // Not a pointer, initialize the instance of your class directly.
    VDorQ24 randomCharacter;
    
    //              v---- Here we send a pointer to your variable using the '&' operator.
    if (VDorQ24Syms(&randomCharacter, szAscii) == /*condition*/)
    {
        return /*value*/;
    }
    

    If you want to send parameter to the constructor, you can use this syntax:

    VDorQ24 randomCharacter{param1, param2};
    

    In fact, any type can be initialized with this syntax, even int and arrays:

    int a{1};
    
    float b[] = {1.f, 2.f, 3.f};