Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Questions: pointers/memory addresses and subclasses

Why are we allowed to run this code:

int* FunctionB(int x)
{
    int temp =30;

    //more code

    return &temp;
}

It seems to me that I am not returning what I said I would. Why is it that a memory address can be returned if I declared the return type to be a pointer. Isn't a pointer something that points to a memory address, not actually a memory address?


class Image : public BMP
{
    public:
    void invertcolors();
    void flipleft();
    void adjustbrightness(int r,int g,int b);

    private:
};

Upon compilation of the previous code I get this error:

image.h:3: error: expected class-name before ‘{’ token

but I thought I was using the proper syntax to declare a sub class. Is there something wrong with what I have written?

like image 776
Arjun Nayini Avatar asked Dec 17 '22 03:12

Arjun Nayini


2 Answers

As far as your first question is concerned

Why are we allowed to run this code:

Nothing can stop you from returning the address of a local variable but that's dangerous(mark my words). Infact return address or reference of a local variable invokes Undefined Behaviour (that means anything can happen).

Also have a look at this.

Why is it that a memory address can be returned if I declared the return type to be a pointer?

That means you have to study the basics on pointers. In computer science, a pointer is a programming language data type whose value refers directly to (or "points to") another value stored elsewhere in the computer memory using its address.

..but I thought I was using the proper syntax to declare a sub class. Is there something wrong with what I have written?

Have you defined BMP or have you included the header which contains its defnition?

like image 179
Prasoon Saurav Avatar answered Dec 24 '22 02:12

Prasoon Saurav


In the first case, a pointer is a memory address, which points to some data, so your syntax is correct. In this case, however, you're returning the address of a local variable, so it's undefined what it'll be pointing to after the function call ends.

In the second case, the compiler is complaining because it doesn't know what BMP is. You may have forgotten to #include the header file for the BMP class.

like image 38
Jesse Beder Avatar answered Dec 24 '22 00:12

Jesse Beder