DEV Community

loading...

C++: Brief answers on basic questions.

supriya2371997 profile image Supriya Kolhe Updated on ・15 min read


1. differences between C and C++?

  1. C is a procedural language, C++ is both procedural and object-oriented programming language.
  2. C was developed in 1969, C++ was developed in 1979
  3. C support OOPS concepts, C++ supports OOPS concepts
  4. C generally known as function-driven language, C++ has generally known as object driven language. 5.C does not support function and operator overloading, C++ support function and operator overloading and also have namespace feature and reference variable functionality.
  5. C has 32 keywords, C++ has 52 keywords
  6. C focuses on methods or process, C++ focuses on data
  7. Exception handling is not supported by C, Exception handling is supported by C++
  8. scanf() and printf() are used for input/output in C, cin and cout are used for input/output in C++

2. differences between references and pointers?

  1. a pointer can be initialized to any value anytime after it is declared, whereas reference must be initialized when it is declared
  2. pointer must be dereferenced with a *, whereas references can be used by name
  3. pointer can be assigned to NULL, whereas references can't be null
  4. pointer can be changed, reference cant be changed to refer to a variable object
  5. pointer has it's own address and stores it on the stack, which can have new values assigned to itself, reference variable shares the same address as the original variable. Also, reference never points to a new variable until the old is deleted it goes out of scope.
  6. pointers can be used when there is a need of data structure or pointer operations, references are commonly used to indirectly access a variable(i.e. can be functions and parameters with return types)

3. C++ access specifiers?

  1. access modifiers can be used to handle data hiding. There are 3 basic access modifiers available, public, private and protected. Each one comes with a set of restrictions. syntax-> access_modifier: data_type variable_name;
  2. By default the access modifier for the members will be private.
  3. public: public members can be accessed by everyone. They can be accessed from anywhere in the program using the member access operator(.) with the object of that class.
  4. private: private members can be accessed directly by the member function or friend function inside the class. They can't be accessed directly by any object or function outside the class. We can also access them using a public member of the class. private members of the base class are inaccessible to the derived class.
  5. protected: it is somewhat similar to private access modifier, in a way that it can't be accessed outside of its class unless with the help of friend class. But protected members can be accessed by any subclass of that class.

4. OOPS?

  1. OOP stands for Object-Oriented Programming and it mainly aims to implement real-world entities like inheritance, hiding etc.
  2. OOP is basically used to gather or bind the data together with the data and the functions that operate on them so that no other part of the code can access this data except that function.
  3. Characteristics : 3.1 class: It is a user-defined data type, which holds it's own data member and member functions. They can be accessed and used by creating an instance of that class.example: consider a class of bike. There can be multiple bikes with different names and brands, but all of them share some common properties like the number of wheels, etc. 3.2 object: It is an instance of a class. The main effect of the object is that it allocates the memory for the class after it is instantiated. It is an identifiable entity with some characteristics and behaviour. After program execution, the objects interact with each other by sending messages to one another. Each object has data and code to manipulate the data. 3.3 inheritance: The process of acquiring the existing functionality of parent and with new added features and functionality of a child Object. A scientific calculator is a extend form of Calculator here Calculator is a parent and the scientific calculator is Child object. 3.4 polymorphism: it gives your system the ability to do the same thing differently for different types of objects i.e An Object is in different forms and in each form its exhibit the same functionality but the implementation is different. A Person who knows more than two languages he can speak in a language which he knows. Here the person is Object and speak is polymorphism. 3.5 encapsulation: As the name suggests, this characteristic is used to wrap the data and functions under a single unit. automatic cola vending machine is an example of encapsulation. Here automatic cola vending machine is a class. It contains both data i.e. Cola can and operations i.e. service mechanism and they are wrapped under a single unit Cola Vending Machine. The working and data are hidden from you. This is possible because that Vending machine is encapsulated so. Thus encapsulation is said to be providing “access control” through which we can control which parts of the program can access the members of any class and thus prevent misuse. Various access controls are public, private and protected. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature, Encapsulation gives maintainability, flexibility and extensibility to our code. 3.6 abstraction: Abstraction means providing the essential features without showing its inner details or hiding internal implementation i.e. This property provides security. The advantage of abstraction is that every user will get his own view of the data according to his requirements and will not get confused with unnecessary data. When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending a request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.

5. Copy Constructor?

  1. it is a member function which initializes an object using another object of the same class i.e The copy constructor in C++ is used to copy data of one object to another. syntax: Class_Name (const Class_Name &old_object);
  2. when to use: 2.1 compiler generates a temporary object 2.2 object is constructed based on another object of the same class 2.3 object returned by value 2.4 object of the class is passed by value as an argument
  3. copy constructor can be private
  4. copy constructor can be explained in a few other ways: 4.1 shallow copy constructor: multiple objects point to the same address, for example, 2 persons are filling the same form at the same time from a different location. The shallow copy constructor is used when class is not dealing with any dynamically allocated memory. 4.2 Deep copy constructor: copying the same data from other objects. but a change in one object will not affect the other object. example student1 copy assignment from student2, and if one of them make any changes in his or her assignment, it will not be affected in other's.

6. reference variable in C++?

  1. reference is an alternative name for an existing variable.
  2. reference can be declared using '&' in the declaration. Syntax: & =Variable;
  3. USES:
    3.1 loop to avoid copy of objects when number of object is large:

    int main() 
    { 
        vector<string> vector_value{"23","07","1997"}; 
        for (const auto &looping_reference : vector_value) 
        cout << looping_reference << endl; 
        return 0; 
    }
    

    3.2 reference received by function can change teh variable value.

    void swapping (int& first_value, int& second_value)
    {
        int temp = first_value;
        first_value = second_value;
        second_value = temp;
    }
    
    int main()
    {
        int one = 23, two = 1997;
        swapping( one, two );
        cout << one << " " << two;
        return 0;
    }
    

    3.3 to avoid wastage of space and memory. passing large value to function can automatically allocate extra memory to the value.

    struct Ground_Staff 
    {
        string name;
        int age;
    }
    
    void print(const Ground_Staff &s)
    {
        cout << s.name << "  " << s.age;
    }
    
  4. references are less powerful than pointers, but they are also easier and safer to use.

7. Extraction and Insertion operators in C++?

  1. Insertion operator << means read data from variable and send it on to the std output device that is VDU. It is used with cout object for displaying variables or text.
    Syntax: cout<<"display_text"<<variable_name;
    It gets its name from the idea of inserting data into the output stream.
    1.1 To display simple message
    cout<<"Message";
    1.2 To display value of a variable
    cout<<var;
    1.3 Mix and match
    cout<<"Message: "<<var

    eg

    int a,b,c;
    cin>>a>>b;
    c = a + b;
    cout<<"Sum = "<<c;

  2. Extraction operator >>means read data from std input device and store at the given location by the variable name. It is used with cin object for reading into variables.
    Syntax: cin>>variable_name; It gets its name from the idea of extracting data from the input stream.
    Since more than one variable can be read in the single statement.
    It is known as cascading input Such inputs can be terminated by
    either of the following

    • A spacebar key
    • A Tab key
    • An Enter key eg

    int a,b;
    cin>>a>>b;

8. Difference between Class and Structure.

  1. class members are private by default, whereas struct member is public by default, it is same in inheritance for both.
  2. class example:

    class CLASS_EXAMPLE
    {
    int var1;
    };
    int main()
    {
    CLASS_EXAMPLE ce;
    // var1 is private, thus compiler error
    t.var1 = 20;
    getchar();
    return 0;
    }

    Struct Example:
    struct STRUCT_EXAMPLE
    {
    int var1;
    };
    int main()
    {
    STRUCT_EXAMPLE se;
    t.var1 = 20;
    getchar();
    return 0;
    }

9. difference between an Object and a class?

  1. object is a instance of a class, whereas class is a blueprint from which objects are created
  2. objecr is a real world entity, whereas class is a group of objects
  3. object can be created many times, class can be declared once.
  4. object is a physical entity, whereas class is a logical entity
  5. object is responsible for allocating the memory to the class when it is created, class does not allocate the memory when it is created
  6. object is created through new keyword and class is declared using class keyword.
  7. there ae many ways to create an object such as new keyword, clone() etc., whereas there is only one way to define a class.

10. this pointer?
The ‘this’ pointer is a constant pointer and it holds the memory address of the current object. It passes as a hidden argument to all the nonstatic member function calls. Also, it is available as a local variable within the body of all the nonstatic functions. As static member functions can be called even without any object, i.e. with the class name, the ‘this’ pointer is not available for them.

11. Pure Virtual Functions?

  1. it is a virtual function i.e. declaring the function and not writing function definition. By default, it assigns 0 in the declaration. (virtual function don't have an implementation) Syntax: virtual data_type function_name()=0; Here =0 does not mean we are assigning 0 to the function, but it's a way of telling the program that we have successfully created a pure virtual function.
  2. it is implemented by classes which are derived from an abstract class.
  3. basically they are used when you are unaware of the implementation but in the know of the functions.
  4. abstract class and pure virtual functions are related in such a way that an abstract class must have at least one pure virtual function.
  5. derived class becomes an abstract class if it does not override the pure virtual function from the parent class. class PURE_VIRTUAL_CLASS { public: virtual void display() = 0; //declared Pure Virtual Function };

void PURE_VIRTUAL_CLASS :: display() //Pure Virtual definition
{
cout << "PURE_VIRTUAL_CLASS display method entered\n";
}

class Derived: public PURE_VIRTUAL_CLASS
{
public:
void display()
{
cout << "Derived display method entered\n";
}
};

int main()
{
PURE_VIRTUAL_CLASS *bp;
Derived d;
bp = &d;
bp->display();
}

12. friend class?

  1. It's a class that has the ability to access private and protected members of other class in which it is declared as a friend.
  2. they are specially used to share the private members.
  3. They should be used only for limited purposes, out of limit use can risk the encapsulation of classes.
  4. friend class works like real-life scenarios, such as if Ankit becomes the friend of Supriya doesn't mean Supriya is a friend of Ankit automatically.
  5. it can't be inherited class Friend_class { private: int number = 23; public: friend class Request_class; }; class Request_class { public: void disp(Friend_class obj) { cout<<obj.number; } }; int main() { Request_class obj; Friend_class obj2; obj.disp(obj2); return 0; }

13. decision making statements in C++?

  1. decision-making statements are used to decide the execution flow of the program depending on certain conditions.
  2. for example: if tomatoes are 20rupees per kg then buy half kg, and if they are 10rupees per kg then buy 1 kilo, and if non of above two conditions are true then do not buy any tomatoes.
  3. types: 3.1 if: if a certain condition is true then a block of statement is executed otherwise not. syntax: if(condition) { // Statements

}
3.2 if-else: when the condition is false and if block does not get executed then else statement is used.
syntax: if (condition)
{
// Statements
}
else
{
// Statements
}
3.3 if else if: it is specifically used when there are conditions to be checked even after prior if the condition fails.
Synatx: if (condition)
{
//statements
}// first if ends
else
{
if (condition)
{
//statements
}//else if ends
else
{
//statements
}//else else ends
}//else ends
3.4 nested if:it means if statement inside another if statement.
Syntax:if (condition1)
{
// Statements
if (condition2)
{
// Statements
}
}
Example: void main( )
{
int a;
cout << "enter number";
cin >> a;
if( a%8==0 && a%3==0)
{
cout << "divisible by both 8 and 3";
}

else if( a%3==0 )
{
cout << "divisible by 3";
}
else if(a%9==0)
{
cout << "divisible by 8";
}
else
{
cout << "divisible by none";
}
}
3.5 break: used to terminate the current loop and transfer the control to the next first loop or statement.
they are commonly used in a switch statement.
Syntax: break;
3.6 continue: it forces to execute the next iteration of the loop.
Syntax: continue;
3.7 switch: it is used when variable needs to be tested for equality against a list of values such as months. Each value is called as a case which can also be a condition or variable or number etc. here default block gets executed when no case block gets executed or there is no break statement before the default block. Here break statement depends on the situation.
switch(expression)
{
case 1 :
//statements;
break;
case 2 :
//statements;
break;
default :
//statements;
}
Example:
switch(1) {
case 1 : cout << '1';
break;

case 2 : cout << '2';
break;
default: cout<<"none";
}
3.8 goto: It is used to transfer control to the other part of the program. It jumps to another label.
Syntax: goto label;
3.9 return: it is used when the flow of the program needs to be stopped immediately and return the control from where it was called. It may not return anything for a void function.
Syntax: return[expression];

14. Data structure?

  1. Linear DS: here data elements are arranged sequentially and elements are attached to its previous and next adjacent. we can traverse all the elements in a single run only. Since the memory consumed by this structure is in sequential form, they are easy to implement and use. They are commonly used in application software development. 1.1 Arrays: it is a fixed size structure which holds elements or values with the same data type. Since they are indexed, randomly accessing elements is possible. An array starts with the 0th index. Syntax: declaration: type arrayName [ arraySize ]; Example: int employeeId[50]; Initializing: type arrayName [ arraySize ]={array_elements};// arraysize is option in this case Example: int employeeId[] = {1000, 2, 3,}; OR arrayName[index]=item/element; Example: int employeeId[2]=56;

1.2 Stack: they work on LIFO strategy i.e. Last In First Out. the element placed at last can be accessed at first.
1.3 Queue: they work on FIFO strategy i.e. the element placed at first can be accessed at first. It is a reverse of the stack.
1.4 LinkedList: A linked list is a sequential structure that consists of a sequence of items in linear order which are linked to each other. They are specifically used when the size is unknown or size changes frequently.

  1. Non-linear: they are not arranged sequentially. we also can’t traverse all the elements in a single run. They are difficult to implement as compared to the linear data structure, but they so utilize the memory in a better way. They are commonly used in image processing and AI. 2.1 Graphs: it consists of nodes and edges. The nodes are sometimes also referred to as vertices and the edges are lines or arcs which connects at least two nodes together. They are commonly used to represent networks and such scenarios. For example, a telephone network. 2.2 Trees: it is a collection of nodes connected to each other by means of “edges” which can be either directed or undirected. One of the nodes is designated as “Root node” and the remaining nodes are called child nodes or the leaf nodes of the root node.

15. stack and Queue? What are the basic operations on them?
Stack: they work on LIFO strategy i.e. Last In First Out. the element placed at last can be accessed at first.
Basic operation:
push(): insert an element into the stack
pop(): remove an element from the stack
peek(): view top element
isFull(): check if stack size if full
isEmpty(): check if stack does not contain any element

Queue: they work on FIFO strategy i.e. the element placed at first can be accessed at first. It is a reverse of stack.
Basic operation:
EnQueue: add an element
DeQueue: remove an element
isEmpty: check if the queue is empty
isFull: check if the queue is full
peek: get front element of teh queue without removing it

16. What is a Linked list? How it is different from an Array?
A linked list is a sequential structure that consists of a sequence of items in linear order which are linked to each other. They are specifically used when the size is unknown or size changes frequently.

  1. array is a collection of similar data type elements, the linked list may or may not contain unordered linked elements.
  2. they are sequential, the linked list may or may not be sequential
  3. array does not save memory as much as the linked list does.
  4. arrays are of fixed length and its size can't be modified, the linked list does not have fixed length and can be modified anytime
  5. arrays are faster than a linked list.
  6. array allocate memory during compile time, whereas linked list allocate memory during execution time
  7. array allow random access, the linked list does not allow random access.
  8. array does not require extra memory for pointer, linked list requires extra memory for the pointers.

17. What is an algorithm?

  1. The algorithms are used to solve problems or provide functionality.
  2. they dont affect size or the storage of the container.
  3. simple algorithm cam be implemented within a function, whereas complex algorithms might require multiple functions to implement them.
  4. language independent i.e. algorithms are not any perticulat programming code, but they are written in such a way that they can be implemeneted using any kind of programming language.
  5. precise algorithms do not end up in an infinite loops or similar.
  6. Example: addition of 2 numbers: step 1: Start step 2: Accept num1, num 2 step 3: Sum= num1+ num2 step 4: Display sum step 5: Stop

18. Explain Multidimensional Array? Give an example of it.

  1. multidimensional array is an array of an array.
  2. they are stored in tabular form
  3. Syntax: data_type array_name[size1][size2]....[sizeN]; Exmaple: int multi_dim[3][4];
  4. a Total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions.
  5. Types: 5.1 2D array: they are an array of 1D array. Synatx: data_type array_name[x][y]; Example: int x[23][07]; OR int x[3][2]={1,2,3,4,5,6}; OR int x[3][2]={{1,2},{3,4},{5,6}}; #include using namespace std;

int main()
{
int 2Darray[3][2]={{1,2},{3,4},{5,6}};
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
cout << 2Darray[i][j]<<endl;
}
}
return 0;
}
5.2 3D array:
it is similar to the 3D array, but the number of dimension increases.
Synatx: data_type array_name[x][y]...[n];
Example: int x[23][07];
OR
int x[2][2][2]={1,2,3,4,5,6,7,8}; OR int x[2][2][2]={{{1,2},{3,4}},{{5,6},{7,8}}};

int main()
{
3Darray[2][2][2]={{{1,2},{3,4}},{{5,6},{7,8}}};
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 2; ++j)
{
for (int k = 0; k < 2; ++k)
{
cout << "[" << i << "][" << j < "][" << k << "] = " << 3Darray[i][j][k] << endl;
}
}
}
return 0;
}

19. Define “Thread”. What is Multithreading?

  1. The thread is a sequence of execution. it can also be referred to as a feature of OS (operating system).
  2. Multithreading behaviour allows the user to perform multiple tasks simultaneously.
  3. Types: UI thread – these are used to create UI components. Eg. Message box pops-out to display any information to the user. Worker Thread – no message pump is included in it
  4. Advantages: Minimizes the context switch time increased and effective communications Easy to handle the threads concurrent processes
  5. multiple ways to create a thread: function pointer function object lambda member function
  6. Multithreading models: Many to many relations Many to One relation One to one relation
  7. #include header file is used

20. Define “Deadlock”.

  1. it is a problem with having to lock two or more mutexes in order to perform an operation.
  2. Often times a deadlock occurs due to wrong order of acquiring locks: multiple threads need to access 2 or more shared resources.
  3. each resource requires mutual exclusion.
  4. For example thread 1 has successfully acquired the lock for resource 1, then tries to acquire the lock for resource 2. While on another CPU core, around the same time, thread 2 has successfully acquired the lock for resource 2 and now tries to acquire the lock for resource 1. Both threads are now stuck. Thread 1 holds resource 1 and waits for resource 2. Thread 2 holds resource 2 and waits for resource 1

21. What do you mean by Client Server?

  1. Client-server denotes a relationship between cooperating programs in an application, composed of clients initiating requests for services and servers providing that function or service.
  2. Example: Client sends a name, the server sends a file with a similar name.
  3. Advantages: 3.1 its centralized architecture helps make it easier to protect data with access controls 3.2 it doesn't matter if the client and server are on the same operating system. 3.3 cost-efficient.
  4. Disadvantages: 4.1 too many clients simultaneously request data from the server, it may get overloaded. 4.2 can cause network congestion 4.3 virus attacks are possible 4.4 DOS attack is possible 4.5 login credentials can be stolen by Man In The Middle attack.

22. How does a Client-Server work?

  1. Browser requests the DNS server for the information regarding URL which was entered by the user.
  2. DNS server then look for the WEB server's address.
  3. DNS server responds with the IP address of the WEB server.
  4. Browser then uses HTTP/HTTPS request to the WEB Server's IP.
  5. Server responds with the necessary files of the website.
  6. Browser then renders the files and websites with the help of DOM interpreter, CSS interpreter and JS engine i.e. JIT or compilers.

Discussion (0)

Forem Open with the Forem app