Introduction to C++

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

What is a key advantage of C++ in terms of platform support?

  • It only runs on Windows operating systems.
  • It can run on any platform with a C++ compiler. (correct)
  • It requires a specific virtual machine to execute.
  • It is limited to running in web browsers.

How does a C++ compiler typically translate .cpp files?

  • Into bytecode for a virtual machine.
  • Into a platform-independent intermediate language.
  • Into an interpreted script.
  • Directly into machine code. (correct)

Which characteristic of C++ makes it suitable for minimizing memory usage and execution time?

  • Its platform independence.
  • Its high-level abstraction.
  • Its direct memory management through pointers. (correct)
  • Its automatic garbage collection.

What type of error is indicated by LNK at the beginning of the error message?

<p>Link error. (B)</p> Signup and view all the answers

Which of the following best describes a pointer in C++?

<p>A variable that stores a memory address. (A)</p> Signup and view all the answers

What is the size, in bytes, of a memory address in a 64-bit system?

<p>8 bytes (C)</p> Signup and view all the answers

What is the purpose of the & operator when used with a variable in C++?

<p>It retrieves the memory address of the variable. (D)</p> Signup and view all the answers

If char a = 65; what will std::cout << a; output?

<p>A (B)</p> Signup and view all the answers

What is the primary difference between the stack and the heap in terms of variable lifetime?

<p>Variables in the heap have a lifetime until the program completes, while those in the stack are scope-limited. (D)</p> Signup and view all the answers

In C++, what is the purpose of a 'copy constructor' when dealing with deep copies?

<p>To create a new object and copy the actual data, not just the pointers, from the original object. (A)</p> Signup and view all the answers

What does the term 'bytecode' refer to in the context of languages like Java, and how does it relate to machine code?

<p>Bytecode is an intermediate representation of code that is converted into machine code by a virtual machine. (C)</p> Signup and view all the answers

What is the lifetime of a variable declared as static inside a function in C++?

<p>It exists from the point of declaration until the end of the program. (B)</p> Signup and view all the answers

What is the meaning of static when applied to a global variable?

<p>The variable is stored in static memory and is only visible within the file it is declared in. (A)</p> Signup and view all the answers

What is the primary purpose of header files in C++?

<p>To declare functions and classes so they can be used in multiple <code>.cpp</code> files. (C)</p> Signup and view all the answers

What is the primary function of the preprocessor directive #pragma once?

<p>It ensures that a header file is included only once during compilation. (B)</p> Signup and view all the answers

When passing a variable 'by reference' to a function in C++, what is the key characteristic of how the function interacts with this variable?

<p>The function receives direct access to the original variable, and any changes modify the original. (B)</p> Signup and view all the answers

In C++, what is the purpose of the virtual keyword in a base class function declaration?

<p>It allows derived classes to override the function and ensures the correct version is called at runtime (dynamic dispatch). (C)</p> Signup and view all the answers

What is a 'pure virtual function' in C++?

<p>A function declared with the <code>virtual</code> keyword that must be overridden in any concrete derived class. (D)</p> Signup and view all the answers

What is the consequence of having a pure virtual function in a class?

<p>It makes the class abstract, meaning it cannot be instantiated. (A)</p> Signup and view all the answers

What is the purpose of a 'member initializer list' in a C++ constructor?

<p>To efficiently initialize member variables, often preventing a default construction followed by assignment. (A)</p> Signup and view all the answers

What is the purpose of the explicit keyword in a C++ constructor?

<p>It prevents the constructor from being used in implicit type conversions. (A)</p> Signup and view all the answers

Given int var = 8; and int* varPtr = &var;, what is the meaning of *varPtr = 10;?

<p>It changes the value of <code>var</code> to 10. (B)</p> Signup and view all the answers

What is the purpose of the new keyword in C++?

<p>It allocates memory on the heap. (C)</p> Signup and view all the answers

What is the difference between delete[] buffer; and delete buffer;?

<p><code>delete[] buffer;</code> is for arrays allocated with <code>new[]</code>, while <code>delete buffer;</code> is for single objects allocated with <code>new</code>. (B)</p> Signup and view all the answers

What is a reference in C++?

<p>An alias for an existing variable. (D)</p> Signup and view all the answers

Given int vaar = 8; and int& ref = vaar;, what happens when you assign a new value to ref (e.g., ref = 2;)?

<p>The value of <code>vaar</code> is also changed to 2, since <code>ref</code> is an alias for <code>vaar</code>. (A)</p> Signup and view all the answers

What is the significance of the const keyword when used in a member function declaration (e.g., int GetX() const;)?

<p>It guarantees that the function will not modify any non-mutable member variables of the class. (A)</p> Signup and view all the answers

What is the mutable keyword used for in C++?

<p>To allow a member variable to be modified even within a <code>const</code> member function. (D)</p> Signup and view all the answers

What is the role of the linker in the C++ compilation process?

<p>It combines the object files and libraries to create an executable file. (C)</p> Signup and view all the answers

What is the primary difference between static linking and dynamic linking of libraries?

<p>Static linking includes the library code directly into the executable, while dynamic linking loads the library at runtime. (A)</p> Signup and view all the answers

What is a potential disadvantage of deep copying objects in C++?

<p>It can be more time-consuming and resource-intensive than shallow copying. (B)</p> Signup and view all the answers

In the context of std::vector in C++, what is the purpose of the reserve() function?

<p>It allocates additional memory to hold a specified number of elements, potentially improving performance by reducing reallocations. (D)</p> Signup and view all the answers

In C++, what is the difference between using push_back() versus emplace_back() when adding elements to a std::vector?

<p><code>push_back()</code> constructs the object in separate memory and then copies or moves it into the vector, while <code>emplace_back()</code> constructs the object directly within the vector's memory. (C)</p> Signup and view all the answers

What is meant by 'pointer arithmetic' in C++?

<p>Incrementing or decrementing a pointer to move it to a different memory location, scaled by the size of the data type it points to. (D)</p> Signup and view all the answers

How do C++ compilers typically handle virtual functions to enable dynamic dispatch?

<p>By creating a v-table (virtual table) for each class, which contains pointers to the correct implementations of virtual functions. (A)</p> Signup and view all the answers

Consider the following code snippet: int stackArray[5]; stackArray[5] = 10;. What is the most likely outcome?

<p>A runtime error or unpredictable behavior will occur, as the code attempts to write beyond the allocated memory for the array. (D)</p> Signup and view all the answers

Given the following code, what is the most accurate description of what will occur?

 int a = 5;
 int& refer = a;
 int b = 10;
 refer = b;

<p>Both <code>a</code> and <code>refer</code> are now 10, while variable <code>b</code> remains 10. (D)</p> Signup and view all the answers

In C++, when should you use a std::unique_ptr over a raw pointer, and what is the primary benefit?

<p><code>std::unique_ptr</code> should be used for single, dynamically allocated objects when exclusive ownership is required; the primary benefit is automatic memory management, preventing memory leaks. (A)</p> Signup and view all the answers

What's the key difference between std::shared_ptr and std::unique_ptr in C++ regarding object ownership and lifetime management?

<p><code>std::shared_ptr</code> enables shared ownership and automatically deallocates the managed object when the last <code>std::shared_ptr</code> is destroyed or reset, while <code>std::unique_ptr</code> provides exclusive ownership and also automatically deallocates its object. (B)</p> Signup and view all the answers

In C++, what is the purpose of std::weak_ptr and how does it relate to std::shared_ptr?

<p><code>std::weak_ptr</code> is a smart pointer that holds a non-owning reference to an object managed by <code>std::shared_ptr</code>, and doesn't prevent the object from being deallocated when the last <code>std::shared_ptr</code> is destroyed. (D)</p> Signup and view all the answers

What are the implications of using macros extensively in C++?

<p>Macros can lead to unexpected behavior due to lack of type checking and scoping, and can make debugging more difficult. (B)</p> Signup and view all the answers

If you have a performance-critical section of code working with a fixed-size array, which of the following would be the most efficient choice in terms of memory management and access speed?

<p><code>std::array&lt;int, size&gt;</code> (C)</p> Signup and view all the answers

Flashcards

Great platform support

Ensures C++ code can run on different operating systems, provided a compiler is available.

Compile time errors

Errors detected during the compilation process of C++ code into object files.

Link errors

Errors encountered when the linker combines object files to create an executable.

Runtime error

Errors that arise after the code has compiled successfully but crashes or misbehaves while the program is running.

Signup and view all the flashcards

Pointer

An integer that stores a memory address, essential for direct memory manipulation.

Signup and view all the flashcards

Variables

Indicates a variable will be placed in either the stack or heap memory.

Signup and view all the flashcards

Primitive data types

They determine how many bytes a variable occupies in memory, dictating the range of values it can store.

Signup and view all the flashcards

Stack memory

Variables stored in stack memory have a lifetime limited by their scope.

Signup and view all the flashcards

Heap memory

Variables stored in heap memory persist until program completion or explicit deallocation occurs.

Signup and view all the flashcards

Data segment

Variables placed in the data segment have a lifetime that lasts the entire program execution.

Signup and view all the flashcards

Static keyword

This is also called a static variable. This controls its visibility and lifespan.

Signup and view all the flashcards

Deepcopy

This refers to creating a completely independent copy of data, especially for arrays, sets, and strings.

Signup and view all the flashcards

Stack

A memory region where variables are stored which is limited by scope and also used for function calls.

Signup and view all the flashcards

Data Segment

A memory region for global/static variables, allocated before runtime and lasting until program completion.

Signup and view all the flashcards

Static member functions

Functions that belong to the class, can only access static vars, and is called using the class name.

Signup and view all the flashcards

Global static variable

A variable that's only visible within the .cpp file it's declared in.

Signup and view all the flashcards

#include

Used for importing content from header files to source files.

Signup and view all the flashcards

#pragma once

A preprocessor directive that ensures a header file is included only once during compilation.

Signup and view all the flashcards

Pass by reference

Passing by reference allows a function to directly modify the original variable.

Signup and view all the flashcards

Struct vs. Class

Structs are public by default while classes are private by default.

Signup and view all the flashcards

Virtual function

A function declared virtual allows derived classes to override its implementation.

Signup and view all the flashcards

Pure virtual function

A function forces subclasses to implement it, ensuring a consistent interface.

Signup and view all the flashcards

V-table

The compiler uses it to map the overriden function at runtime.

Signup and view all the flashcards

Member initializer list

A container of variables that can be initialized within a constructor.

Signup and view all the flashcards

int main

The entry point of a C++ program and ran by default.

Signup and view all the flashcards

& (Address-of operator)

The & symbol gets the memory address of a variable.

Signup and view all the flashcards

  • (Dereference operator)

The * derefences/gets the value at a memory address.

Signup and view all the flashcards

new allocates memory on heap using MALLOC

Functions like malloc allocates memory on heap while calls the OS function. The OS allocates the requested memory and returns the address.

Signup and view all the flashcards

Macros

The preprocessor replaces your code before compilation.

Signup and view all the flashcards

Templates

Allows us to create a function or class that can work with any type.

Signup and view all the flashcards

Lambda function

Also known as anonymous function which captures variables that are scoped within the lambda function.

Signup and view all the flashcards

Namespace

Used to avoid naming conflicts.

Signup and view all the flashcards

Threads

These are used as a means of splitting your program into multiple code paths (threads) and can run in parallel.

Signup and view all the flashcards

Mutex

This locks a thread so that no other thread can access the resource at the same time.

Signup and view all the flashcards

Compiler/Linker Process

When the compiler transforms C++ code into machine code and the linker then links the different .obj files together.

Signup and view all the flashcards

Study Notes

  • C++ benefits from great platform support, enabling code execution on any platform with a compiler.
  • C++ compiles directly to machine code, resulting in fast execution speeds.
  • Java and other similar languages runs on a virtual machine.

Low-Level Control

  • C++'s low-level nature grants control over memory allocation through pointers, making it suitable for applications requiring memory and time optimization.

Error Types

  • Compile-time errors occur during the translation of .cpp files into object files.
  • Link errors arise when the linker combines object files, often indicated by "LNK" prefixes.
  • Runtime errors manifest post-compilation, leading to crashes or unexpected behavior.

Pointers

  • Pointers store memory addresses, treating memory as a linear sequence.
  • The asterisk * symbolizes a pointer, while & retrieves a variable's address.
  • Pointer size is 4 bytes on 32-bit systems, equating to 32 bits, which can address 2^32 memory locations.
  • Pointer size is 8 bytes on 64-bit systems.
  • Bytes are represented by 2 hexadecimal.

Variables

  • Variables are stored in memory, either on the stack or the heap.
  • Primitive data types determine variable sizes in bytes.
  • Code handles variables based on their declared data types.
  • The statement char a = 65; std::cout << a; treats 65 as a character, outputting 'A'.
  • int occupies 4 bytes, with one bit indicating the sign.
  • unsigned int values are always positive, employing the sign bit to expand the maximum positive range.
  • The unsigned keyword can be applied to any data type to remove the sign bit.
  • Common data types and their sizes:
  • char: 1 byte
  • short: 2 bytes
  • long: 4 bytes
  • long long: 8 bytes
  • float: 4 bytes
  • double: 8 bytes
  • bool: 1 byte
  • Although a boolean value could technically be represented by a single bit, the smallest addressable unit in memory is a byte.
  • 1 byte can store 8 boolean values.

Deepcopy

  • Deepcopy is often used for arrays, sets, strings, in which the instance contains a pointer, requiring instance variables.
  • This copies the pointed memory rather than just the pointer itself, preventing issues of "shallow" copies where multiple objects point to the same data, leading to unintended modifications.
  • C++ supports copy constructors for creating deep copies.

Memory Segments: Heap, Stack, and Data

  • Heap: Variable lifetime extends until the program's completion. Memory is freed upon variable deletion but not zeroed out.
  • Stack: Stores variables with lifetimes limited by their scope, along with function calls. Memory is considered unallocated but retains old values.
  • Data segment: Stores global and static variables allocated before runtime, persisting until the program ends.

Static Keyword

  • Static controls linkage and lifetime, placing variables in the data segment.
  • Static variables are initialized only once before program execution begins.
  • Inside a function, a static variable belongs to that function as a nonlocal variable.
  • Inside a class, it belongs to the class itself.
  • A global static variable is confined to the .cpp file it's declared in.
  • Static local variables retain assigned memory locations throughout a program's execution.
  • Static member variables remain in memory until the program finishes and must be initialized like global variables.
  • Static members are shared among all class instances, belonging to the class rather than specific instances.
  • Can be accessed even if the class has not been instantiated in main
  • They cannot access non-static members because they belong to the class, not the instance.
  • Static member functions belong to the class and can only access static variables, callable via the class name.
  • Global static variables are visible only within their containing .cpp file.

Preprocessor Directives

  • #include <iostream> looks for the iostream file and copies all the content into the current file
  • #pragma once includes the this file only once

Pass by Reference

  • "address individual bits" cannot be done, only bytes.
  • Pass by reference means the function modifies the original variable.

Classes

  • Member variables are private by default.
  • Structs are the same as Classes, except members are public by default.
  • Use structs to only hold and manipulate data. Nothing else.
  • Static members are shared among all instances. You must declare it (outside the class) in the .cpp file as int Player::shared_var;

Virtual Functions

  • When using inheritance in classes
  • Compiler uses V-table to perform dynamic dispatch
  • V-Table stores virtual functions of the base/parent class
  • Virtual function causes extra memory and extra time (to look up V table)

Pure Virtual Function

  • abstract methods within a class
  • base class doesn't have full implementation
  • enforce subclasses implementation
  • cannot instantiate that class
  • virtual void anAbstractMethod() = 0;

Member Initializer List

  • Use to initialize member variables of a class
  • explicit InitializerExample(std::string n) : name(n)

Pointers

  • Double Pointer double* points to double values
  • For While loops "execute code once no matter what"
  • Use preprocessor to replace code before compilation

Stack versus Heap

  • Stack: has predefined size and limit. Gives us memory by moving a pointer but we can't change the pointer. (is VERY FAST)
  • Heap: new keyword allocates memory on the heap using malloc. (IS MUCH SLOWER)

Macros

  • Kinda like find and replace
  • Example: #define WAIT std::cin.get()
  • But don't do that

Auto

  • Type inference
  • Compiler infers the type of whatever you initialized something with

Static Array

  • Stores size, and throws out of bounds errors, as well, unlike normal arrays

Function Pointers

  • Void (*pointerName)(const char*) = &Log;

Lambda Function

  • Anonymous function, since they don't have explicit names
  • Function that is defined inline
  • Use capture to use outside variables inside the lambda function via []
  • Everything we captured is in capture scope

Namespace

  • Use to avoid naming conflicts

Threads

  • To start a Thread you must pass in a void function
  • Mutex locks a thread so no other thread can access it at the same time. This must be unlocked as well.
  • Compiler transforms C++ code into machine code.
  • If you get an error, prints output at compile time
  • Then Linker links the code together.
  • Converts the cpp into obj files

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

C++ Basics PDF

More Like This

Pointers in C++
8 questions

Pointers in C++

MercifulFaith avatar
MercifulFaith
Pointers in C++
5 questions

Pointers in C++

FavoredLearning4069 avatar
FavoredLearning4069
Use Quizgecko on...
Browser
Browser