answersLogoWhite

0

📱

C++ Programming

Questions related to the C++ Computer Programming Language. This ranges all the way from K&R C to the most recent ANSI incarnations of C++, including advanced topics such as Object Oriented Design and Programming, Standard Template Library, and Exceptions. C++ has become one of the most popular languages today, and has been used to write all sort of things for nearly all of the modern operating systems and applications." It it a good compromise between speed, advanced power, and complexity.

2,546 Questions

What is difference between call by value and pass by value?

When you pass by value, the function's parameter is assigned the value of the argument that was passed. When you pass by reference, the function's reference parameter is assigned the address of the argument. In other words, pass by value copies the value, pass by reference passes the variable itself.


Pass by reference is always the preferred method of passing arguments to functions when those arguments are complex objects. If the argument is a primitive data type then the cost in copying the value is minimal, but copying a complex object is expensive in terms of performance and memory consumption. If the function parameter is declare constant, you can be assured the object's immutable members will not be affected by the function. If it is non-constant and you do not wish your object to be altered, you can either copy the object and pass the copy, or pass the object by value if the function is overloaded to cater for this eventuality (good code will provide both options).



How many pointers can be used in a c program?

Answergenerally we use simple pointer, void pointer,null pointer, structure pointer. Answerzero or more (unlimited).

What is queue in c plus plus?

A queue is a FIFO data structure. The best way to implement this is to use two pointers, one to track the head and one to track the tail. During a push operation, the tail pointer will advance one spot as the data is entered into the list. During a pop operation, the head pointer will advance one spot as data is removed. When the two pointers are pointing to the same space, the queue is empty.

What is the default return type of a function?

The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value. By default, it will return zero.

To learn more about data science please visit- Learnbay.co

What is Constructor in C plus plus?

A constructor is a special class method that instantiates an object of the class.

All objects must have at least two constructors, one of which must be a copy constructor. Even if you do not explicitly declare a copy constructor, one is generated for you with public access by the compiler. The purpose of the copy constructor is to instantiate new objects from existing objects. Even if you never explicitly call the copy constructor, it is automatically called whenever you pass an object to a function by value, as the object must be copied.

If you do not declare any constructors, then both the copy constructor and the default constructor are generated for you. The default constructor is a constructor that accepts no parameters, or that is declared with all default parameters.

Although the compiler will generate default and copy constructors for you, it is always recommended that you declare your own constructors, thus ensuring your object members are always correctly initialised and valid. An uninitialised object is a potential time-bomb.

Constructors are not functions; they do not return any value, not even void. The assignment operator (which does return a value) is not a constructor; it is used to initialise an existing object from another existing object -- it does not instantiate a new object.

Constructors are called whenever you instantiate a reference to an object, or allocate memory to an object using the new operator, or copy a new object from an existing object.

All constructors have the same name as the class itself. Construction overloads can be differentiated by their signature (the number and type of parameters they accept). The copy constructor is signified by the fact its only parameter is a constant reference to an object of the same class.

class Object

{

public:

Object(); // Default constructor (no parameters)

Object(const Object& object); // Copy constructor

Object(int x); // Overloaded constructor

}

As well as constructors, it is recommended you also declare your own assignment operator and destructor. Even if the compiler-generated versions are adequate for your needs, it costs nothing but a little time to declare your own. But if your class allocates dynamic memory on the heap, you must include code in the constructors, destructor and assignment operator to ensure that memory is correctly initialised and released, and that self-references are correctly accounted for; the compiler-generated methods will not do it for you.

How do you write a program in linked list in ascending and descending order in sorted way using c plus plus?

#include <stdio.h>

#include <conio.h>

int main()

{

int a[10],i,j,temp=0;

printf("Enter all the 10 numbers");

for(i=0;i<10;i++)

scanf("%d",&a[i]);

for(i=0;i<10;i++) //This loop is for total array elements (n)

{

for(j=0;j<9;j++) //this loop is for total combinations (n-1)

{

if(a[j]>a[j+1]) //if the first number is bigger then swap the two numbers

{

temp=a[j];

a[j]=a[j+1];

a[j+1]=temp;

}

}

}

printf("The ordered array is");

for(j=0;j<10;j++) //Finally print the ordered array

printf("%d \t",a[j]);

getch();

return 0;

}

Write a program in c plus plus in which insertion and deletion in an array?

#include<stdio.h>

#include<conio.h>

void main()

{

int a[10],i,j,k,n;

printf("enter number of elements of array");

scanf("%d",n);

printf("Enter array elements");

for(i=1;i<=n;i++)

{

scanf("%d",a[i]);

}

printf("enter the element you want to delete");

scanf("%d",k);

for(j=0;j<n;j++)

{

if(a[j]==k)

{

a[j]=a[j+1];

n=n-1;

}

}

printf("The array after deletion of %d is:",k);

for(i=1;i<n;i++)

{

printf("%d",a[i]);

}

getch();

}

Why are pointers important in C plus plus?

Pointers are variables. They allow you to store memory addresses and to indirectly manipulate the contents of those memory addresses. Pointers can point to variables, constants and functions -- anything that resides in memory -- so long as the type of the pointer is covariant with the type being pointed at. Pointers that are no longer in use should be nullified by assigning the value NULL, thus preventing indirect access to memory that may no longer be in scope.

In C, a pointer is no different to a reference, hence we use the term 'dereference' when indirectly accessing the value of a pointer (the memory being pointed at). But in C++, a reference is not a variable of any kind, it is simply an alias that you can use in your source code to refer to an instance of an object, function, variable or constant. C++ references must be initialised at the point of instantiation, and are not unlike constant pointers. However, unlike references in C, references in C++ can never be NULL (a NULL reference will invalidate your program).

How you calculate rand in c plus plus?

Use the random number generator classes.

#include<random>

#include<ctime>

std::default_random_engine generator ((unsigned)time(0)); // seed the generator

std::uniform_int_distribution<int> distribution (0, 100); // set the closed range

int r = distribution (generator); // pick a random number from 0 to 100 (inclusive)

Any device can be used to seed the generator. Here, we've simply used the current time. If you don't seed the generator, it will generate the same sequence of random values every time the program is run.

What is the main purpose of using comments in c plus plus?

The main advantage of the newer C++ comment syntax is that you only need to start the comment, and you can expect that it will last only until the end-of-line. With the older syntax, you needed to also stop the comment. any statement; /* old comment syntax */

any statement; // new comment syntax

What is casting in java and c plus plus?

Implicit casting is done automatically by the compiler and virtual machine.

Explicit casting is needed to convert types of data when Java is not sure if the result will be valid. There are two times when you will need to perform explicit casts: casting between primitives and casting between objects.

  1. Between primitives: Primitive types come in different sizes. For example, an int is 32 bit, whereas a long is 64. If you are sticking a smaller type into a larger type (eg. an int into a long), there is no need to cast since there is no risk that the value will be larger than its container. However, when you go in the opposite direction (eg. a long into an int), a compilation error will occur since Java is afraid the value will be too large for its type. To "silence" the compiler, you can cast the value to the intended type. In doing so, you risk the value overflowing its container. (Example below)
  2. Between objects: There are two types of object to object casts: upcasts and downcasts. Upcasting occurs when you take a subclass and stick it in a more general type (Object o = new String();). Upcasting is always implicit. Downcasting is going in the opposite direction. You always need to explicitly cast when downcasting, and Java will only allow you to do so if the conversion is possible. (Example below).

Examples between primitives:

byte b; short s;

s = b; //valid

b = s; //invalid

b = (byte)s; //valid

b = (byte)Short.MAX_VALUE; //valid, but overflow will occur.

Examples between objects:

Object o = s; //upcast - no explicit casting required

String s = (String)new Integer(); //always a compile error

String s = (String)getObject(); //assume that getObject() returns type Object. This will only work if the value stored in getObject() is a String or a subclass of String. Otherwise a runtime error will occur.

What are the 42 keywords in turbo c?

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

Explain static data member with the help of example?

Yes. Static data members are local to the class in which they are declared. Thus all instances of the class share the same variables (unlike non-static data members where each instance of the class has its own set of variables). Moreover, since static data members do not belong to any instance of the class, they are accessible without the need to instantiate an instance of the class, and like all other static variables, remain in scope for the entire duration the program is running. Also, as with all other static variables, they must be initialised at compile time from outside of the class declaration. Usually this is done from the class CPP file.

Static member functions are similar to static data members in that they are local to the class, rather than to an instance of the class. Since they do not belong to any instance of the class, they do not inherit an implicit this pointer. As a result, they are accessible without the need to instantiate an instance of the class and will remain in scope for the entire duration the program is running.

It is not unusual for a class to have both static data members and static member functions. They can be likened to global variables and global methods, but scoped to the class. However, their visibility can be restricted by the access specifiers enforced upon them (public, protected or private). Although static member functions cannot access instance methods and instance variables (unless an instance is physically passed to them as an argument) they have unrestricted access to the static data members of the class, as do all instances of the class and friends of the class.

A classic example of static member functions and static data members in the same class is when one needs to maintain a count of all instances of a class. All the class constructors must increment the static counter while the destructor must decrement it. A static member function such as GetCount() can then report the number of instances currently instantiated, even when there are no instances.

There are many other uses, but the golden rule is that they must be related to the class in which they are declared. If their purpose is simply to provide global functionality then declare them as such, or (better) limit their scope by declaring them in a separate class specifically for that purpose with private constructors to prevent any instances from being created (since none would be required).

How do you write a program to arrange the elements in ascending order by using selection sort technique?

#include<iostream>

#include<vector>

template<class T>

void insertion_sort (std::vector<T>& v)

{

if (v.size()<2U)

return;

for (size_t index=1; index<v.size(); ++index)

{

T value = v[index];

size_t gap = index;

size_t prev = index-1;

while (gap && value<v[left] )

v[gap--]=v[left--];

v[gap] = value;

}

}

int main()

{

std::vector<int> vect {42, 1, 27, 8, 15, 4};

for (auto v : vect) std::cout << v << '\t';

std::cout << std::endl;

insertion_sort (vect);

for (auto v : vect) std::cout << v << '\t';

std::cout << std::endl;

}

How do you use C plus plus code in Java Program?

You don't. There are two possible workarounds.

  1. Use the Java Native Interface (JNI). JNI code resembles C-style code and is able to be compiled in the native machine language of the underlying system. This is a rather complicated solution, and is not ideal for a "quick fix."
  2. Write your C++ code like normal, compile it, and use Java code to call your compiled code. You can use the Runtime.getRuntime().exec() methods to accomplish this.

How to calculate sum of two complex number in c plus plus?

typedef struct complex {

double real, imag;

} complex;

...

complex x, y, z;

...

/* add */

z.real = x.real + y.real;

z.imag = x.imag + y.imag;

/* sub */

z.real = x.real - y.real;

z.imag = x.imag - y.imag;

/* mul */

z.real = x.real*y.real - x.imag*y.imag;

z.imag =x.imag*y.real + x.real*y.imag;

/* div */

double d = y.real*y.real + y.imag*y.imag;

z.real = (x.real*y.real + x.imag*y.imag)/d;

z.imag = (x.imag*y.real - x.real*y.imag)/d;

What is the importance of using an array in C plus plus programming?

When there is a need of storing a list of same type of large no. of data in linear manner,it is ridiculous to use large no. of different variables.It is more complex also.So in c and c++ array is used.
If the ans helps you,plz increase the trust point.

What object in c plus plus?

An object is an instance of a class. A class is a user-defined data type from which we can instantiate objects of that class. We often use the terms object and variable interchangeably, however the term variable specifically refers to a named object (objects instantiated at compile time), as opposed to anonymous objects (instantiated at runtime). Built-in data types such as int, double and pointer types are not classes, thus instances of these types are simply known as variables. Built-in types are also part of the language (hence they are built-in) thus we don't need to include a header or a type definition in order to use them; they are immediately available. But to use an object we must first define its class or include the appropriate header that defines the class.

How do you write a c plus plus program to calculate number of days between given date's?

#include<stdio.h>

#include<conio.h>

#include<time.h>

time_t time(time_t *t);

main()

{

int y2,m2,d2,y,m,d;

time_t t = time(NULL);

struct tm tm = *localtime(&t);

printf("Time now: %d-%d-%d %d:%d:%d\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);

y2=tm.tm_year+1900;

m2=tm.tm_mon+1;

d2=tm.tm_mday;

printf("Enter the Reference Date in DD MM YY format\n");

scanf("%d%d%d",&d,&m,&y);

int loop,total_days = 0,days_in_a_year;

int day,month,year;

int month_days[] = {31,28,31,30,31,30,31,31,30,31,30,31};

printf("\n%d\n%d\n%d\n",(y2-y),(m2-m),(d2-d));

printf("%d",month_days[m]);

if(((y2-y)==0&&(m2-m)<1&&(d2<d))(y2<y)(m<1)(m>12)(d<0)(d>month_days[m-1]))

{

printf("\nInvalid Reference Date\n");

}

else

{

total_days=month_days[m-1]-d;

if((m==2)&&((y%4)==0))

total_days+=1;

for(int i=m;i<12;i++)

{

if((y%4==0)&&i==1)

total_days+=1;

total_days+=month_days[i];

}

for(int year=y+1;year<y2;year++)

{

if(year%4==0)

total_days+=366;

else

total_days+=365;

}

for(int i=0;i<m2-1;i++)

{

if((y2%4==0)&&i==1)

total_days+=1;

total_days+=month_days[i];

}

total_days+=d2;

if((y2==y)&&(y%4==0))

total_days-=366;

if((y2==y)&&(y%4!=0))

total_days-=365;

}

printf("\nThe date difference is %d\n",total_days);

getch();

}

What is public in c plus plus?

public is an access-modifier that allows you to access methods or properties of a class from outside of the class. A method or property set to protected can only be accessed from within the creating class or subclasses, while a private method or property can only be accessed from within that class

Write a C plus plus program to interchange two numbers by using function?

#include<iostream>

template<typename _Ty>void swap (_Ty& a, _Ty& b)

{

_Ty temp = a;

a = b;

b = temp;

}

int main()

{

int x = 42;

int y = 0;

std::cout << "Before swap:" << std::endl;

std::cout << "x = " << x << ", y = " << y << std::endl;

swap (x, y);

std::cout << "After swap:" << std::endl;

std::cout << "x = " << x << ", y = " << y << std::endl;

}

Example Output

Before swap:

x = 42, y = 0

After swap:

x = 0, y = 42

Write a program that sorts an array of integers using pointers?

#include "stdio.h"

#include "stdlib.h"

#include "string.h"

#define MAX 50

#define N 2000

void sort_words(char *x[], int y);

void swap(char **, char **);

int main(void)

{

char word[MAX];

char *x[N];

int n = 0;

int i = 0;

for(i = 0; scanf("%s", word) == 1; ++i)

{

if(i >= N)

printf("Limit reached: %d\n", N), exit(1);

x[i] = calloc(strlen(word)+1, sizeof(char));

strcpy(x[i], word);

}

n = i;

sort_words(x, n);

for(i = 0; i < n; ++i)

printf("%s\n", x[i]);

return(0);

}

void sort_words(char *x[], int y)

{

int i = 0;

int j = 0;

for(i = 0; i < y; ++i)

for(j = i + 1; j < y; ++j)

if(strcmp(x[i], x[j]) > 0)

swap(&x[i], &x[j]);

}

void swap(char **p, char **q)

{

char *tmp;

tmp = *p;

*p = *q;

*q = tmp;

}

Do Write a program in c plus plus to enter 10 voters age and display the average male voters age and average female voters age using loop?

#include<iostream>int main () {

int age, female=0, male=0, fcount=0, mcount=0;

char sex;

for (int voter=0; voter<10; ++voter) {

std::cout << "Enter the voter's age and gender: ";

std::cin >> age >> sex;

switch (sex) {

case 'm':

case 'M': ++mcount; male += age; break;

case 'f':

case 'F': ++fcount; female += age; break;

}

}

std::cout << "Average male age: " << male / mcount << std::endl; std::cout << "Average female age: " << female / fcount << std::endl;

}

Is C plus plus a query language?

No. Standard C++ has no dependencies whatsoever, unlike Java which is entirely dependent upon the Java Virtual Machine, and Visual Basic, C# and F# which are all dependent upon Windows, the Common Language Runtime and the .NET Framework. Platforms may impose dependencies upon C++, but C++ itself has none of its own.