Tag Archives: const

Covering C++ interviews questions on const, initialization list, global variables, and static

Covering C++ interviews questions on const, initialization list, global variables, and static
Note that non static const data members and reference data members cannot assign values. You would need to have these initialized in the initialization list.

Initialization lists can be listed as private after the constructor definition.
class Baz
{
public:
Baz() : _foo( “initialize foo first” ), _bar( “then bar” ) { }

private:
std::string _foo;
std::string _bar;
};

In order to access non static members of a class from a static method, you need to declare a class instance inside the static instance. A static method can only use in class’s role is to use static members only. Static methods can be accessed by non static and static data members. Static methods cannot be volatile, constant, or virtual. Also for example, for app.cpp or app.c:
static void print_some_data()
{
}
is limited in abc.cpp/c only, no other compilation unit in an application can use it.

A common use for static to keep track the number of instances of a class.
Static member functions are used to access private static data member and they do not have a this pointer. They can only access static data members as they are not attached to instances of objects.
To access static member of a class, use ::
In short:
1. Within a function, there is one copy of the variable that retains its value even when the function returns.
2. Within a class, all objects share the static variable and the static variable is accessed using the class name.
3. In the global scope a static variable is local to the current file.

2.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Passing by References versus raw pointers in C++. Const also covered

Passing by References versus raw pointers in C++. Const also covered
References need to be initialized during declaration (i.e. int &i=10;) and they cannot contains values of null. They are an implicit pointer, they do not require dereferencing, no memory address required, and are safer then pointers.
Pointers offer advantages over references including they do not need to be initialized, program may need nulls so use pointers, and they can be stored in containers.

You should only initialize a reference within a non static member list so you should initialize references in constructors. It is also safer to pass by reference versus pointers. You should also pass by reference if there is expected large amount of memory being passed to functions.

Pre-pending an ampersande ( & ) makes a variable or object a reference. For example,
Int a;
Int b=&a;

Below is an example of passing by reference:
void swap( int & x, int & y )
{
int temp = x;
x = y;
y = temp;
}
int a=2, b=3;
swap( a, b );

No extra memory is needed so it makes passing by reference very efficient.

You should also use “const” reference arguments as well. Because of const, it will inadvertently protect your data that could get altered, passing without a const only enables you pass a non const only, and using const reference allows the function to generate temporary variables. This is a corrected example:

#include
using namespace std;

double Cube( const double & num)
{
double result;
result = num * num * num;
return result;
}

int main() {
long temp = 4L;
double x = 3;
double value = Cube ( temp ); // long to double conversion
cout << "v= " << value << endl; return 0; }

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ Storage classes and qualifiers like auto, extern, register, volatile, const, mutable

C++ Storage classes and qualifiers like auto, extern, register, volatile, const, mutable

C++ storage classes include:
Auto: This is the default where variables are automatically created when they are defined and are destroyed at the end of a block containing their definition. They are also not visible outside of their defined block.
Register: This is similar to auto variable but suggests to the compiler to use a CPU register for performance.
Extern: A static variable that is whose definition and placement is determined when object and library modules are combined (also known as linking) to form the executable code file. It can also be visible outside of where it is defined as well. Both C and C++ require that symbols are only defined in a single translation unit (file.c|file.cpp). The extern keyword tells the compiler that a symbol is only a declaration – it is defined somewhere else. If you only ever include a header in a single .c-file, you can get away without the extern. However, if you include it in more than one, the linker will see the same symbol defined in more than one translation unit (one for each .c[pp] file including the header) and rightly flag it as an error.
Storage qualifiers:
Const keyword indicates that memory once initialized cannot be altered by the program.
Volatile keyword indicates that the value at a particular memory location can be altered event though in the program modifies its content. Volatile is to improve the compiler optimization. The volatile keyword is a type qualifier used to declare that an object can be modified in the program by something (external resources) such as the operating system, the hardware, or a concurrently executing thread. For example,
Mutable keyword indicate particular data member of a structure or class can be altered even if a particular variable is defined in a class member function as being const.
structure variable, class, or class member function is constant.
struct data
{
char name[80];
mutable double salary;
}
const data MyStruct = { “Satish Shetty”, 1000 }; //initlized by complier
strcpy ( MyStruct.name, “Shilpa Shetty”); // compiler error
MyStruct.salaray = 2000 ; // complier is happy allowed

?
int volatile nVint;

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview question: Copy Constructor vs assignment operator with const

C++ interview question: Copy Constructor vs assignment operator with const

Structures and classes are the same. The only difference is that structures are defaulted at being public while classes are defaulted at being private. Structures are a C feature so they do not have any C++ features like inheritance.
Copy constructors can overload the assignment operator to allow deep copying instead of default shallow coping. This invoked when one object is initialized to make another.
Both copy constructor and assignment operator are the same where they perform shallow copies by default. As said, you can override the default copy constructor or overload the assignment for deep copies. An KEY DIFFERENCE sample is:
sample x1=x2; //call copy constructor
sample x1;
x1=x2l //calls assignment operator
Copy constructors need a const so that the constructor does not change the state of where it is copying from. This means it cannot be altered within the function. If a function attempts to change the value, the program will not compile. It is advised to use a const in very constructor parameter. Be advised of this potential compiler error:
Foo::Foo(Foo&) {} /constructor without const
const Foo a;
Foo b(a);// error
In a nutshell remember,
1. Copy-Constructor without ‘const’ compiles.
2. Copy-Constructor without ‘const’ is called.
3. ‘const’ in CC prevents passd object from being modified.

There are numerous reasons why you should never call a virtual method from a derived class constructor. This loses its meaning as it will case its base implementation instead.

Also, you should note order of execution in this code:
#include
using namespace std;

class Base{
public:
Base(){cout << "Base()" << endl;} Base(const Base&){cout << "Base(const Base&)" << endl;} ~Base(){cout << "~Base()" << endl;} }; Base func(Base b){return b;} void test1(){ Base a; func(a); } void test2(){ Base a; Base b = func(a); } int main(){ test1(); test2(); return 0; } Output is: Test1 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Test2 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Reasons are: Test1 Step-1 Default constructor will be called at Base a; Step-2 Copy constructor will be called when passing a as formal parameter i.e func(a). Step-3 Copy constructor will be called for return object. Step-4 Destructor will be called for actual parameter of func. Step-5 Now this return obj will act as nameless obj in test1() and will get destroyed after line func(a) calling destructor one more time. Step-6 Finally Destructor will be called for a. You can see same for test2();

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!