Skip over navigation

Contents

Pointers and Basic Structures in C++

Problems

Pointers

Other Data Structures

Problem : What is the difference between a pointer to a variable and the variable itself?

A pointer holds an address, or location in memory, instead of simply storing a value.

Problem : Can a pointer point to any data type?

Yes. Just be sure to specify the data type it will point to when it is declared. That is, float* p tells the computer to create a pointer to a floating point number, whereas class_name* q tells the computer to create a pointer to an object of type class_name.

Problem : Why use pointers?

Pointers are most useful when you need to pass a variable by reference instead of value, and when you need to create a special structure like a linked list, whose size you do not know ahead of time. In addition, pointers allow C++ programmers to take advantage of a property known as polymorphism.

Problem : What is the difference between passing by value and passing by reference?

Passing by value gives a function the value of a variable, and the function creates an entirely new variable with the same value. This protects the original variable from modification. Passing by reference gives the function the address of a variable, so the original variable is vulnerable to modification.

Problem : When are structs useful?

Structs are used to create a new data type that should contain two or more related components.

Follow Us